From 2ad405f3ad8bd15776b063d94f2e7ee01a7baf0c Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 11 Oct 2024 14:42:47 -0500 Subject: [PATCH 01/11] docs(readme): update and remove refs to deprecated services --- README.md | 84 +++++++++++++++++++++++++++---------------------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index a0aea98d..e99a46d4 100755 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ The file downloaded will be called `ibm-credentials.env`. This is the name the S As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following: ```python -discovery = DiscoveryV1(version='2019-04-30') +assistant = AssistantV2(version='2024-08-25') ``` And that's it! @@ -122,7 +122,7 @@ export ASSISTANT_AUTH_TYPE="iam" The credentials will be loaded from the environment automatically ```python -assistant = AssistantV1(version='2018-08-01') +assistant = AssistantV2(version='2024-08-25') ``` #### Manually @@ -142,15 +142,15 @@ You supply either an IAM service **API key** or a **bearer token**: #### Supplying the API key ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator # In the constructor, letting the SDK manage the token authenticator = IAMAuthenticator('apikey', url='') # optional - the default value is https://iam.cloud.ibm.com/identity/token -discovery = DiscoveryV1(version='2019-04-30', +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) -discovery.set_service_url('') +assistant.set_service_url('') ``` #### Generating bearer tokens using API key @@ -166,36 +166,36 @@ token = iam_token_manager.get_token() ##### Supplying the bearer token ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator # in the constructor, assuming control of managing the token authenticator = BearerTokenAuthenticator('your bearer token') -discovery = DiscoveryV1(version='2019-04-30', +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) -discovery.set_service_url('') +assistant.set_service_url('') ``` #### Username and password ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import BasicAuthenticator authenticator = BasicAuthenticator('username', 'password') -discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) -discovery.set_service_url('') +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) +assistant.set_service_url('') ``` #### No Authentication ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator authenticator = NoAuthAuthenticator() -discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) -discovery.set_service_url('') +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) +assistant.set_service_url('') ``` ### MCSP @@ -221,17 +221,17 @@ Tested on Python 3.9, 3.10, and 3.11. If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+python). -## Configuring the http client (Supported from v1.1.0) +## Configuring the http client To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://requests.readthedocs.io/en/latest/api/) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2021-11-27', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') @@ -248,12 +248,12 @@ To use the SDK with any proxies you may have they can be set as shown below. For See this example configuration: ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2021-11-27', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') @@ -268,12 +268,12 @@ assistant.set_http_config({'proxies': { To send custom certificates as a security measure in your request, use the cert property of the HTTPS Agent. ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2021-11-27', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') @@ -322,14 +322,14 @@ For example, to send a header called `Custom-Header` to a call in Watson Assista the headers parameter as: ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2018-07-10', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) -assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') +assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() ``` @@ -339,14 +339,14 @@ response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}). If you would like access to some HTTP response information along with the response model, you can set the `set_detailed_response()` to `True`. Since Python SDK `v2.0`, it is set to `True` ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2018-07-10', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) -assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') +assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') assistant.set_detailed_response(True) response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() @@ -372,9 +372,9 @@ Every SDK call returns a response with a transaction ID in the `X-Global-Transac ### Suceess ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 -service = AssistantV1(authenticator={my_authenticator}) +service = AssistantV2(authenticator={my_authenticator}) response_headers = service.my_service_call().get_headers() print(response_headers.get('X-Global-Transaction-Id')) ``` @@ -382,10 +382,10 @@ print(response_headers.get('X-Global-Transaction-Id')) ### Failure ```python -from ibm_watson import AssistantV1, ApiException +from ibm_watson import AssistantV2, ApiException try: - service = AssistantV1(authenticator={my_authenticator}) + service = AssistantV2(authenticator={my_authenticator}) service.my_service_call() except ApiException as e: print(e.global_transaction_id) @@ -396,9 +396,9 @@ except ApiException as e: However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace `` in the following example with a unique transaction ID. ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 -service = AssistantV1(authenticator={my_authenticator}) +service = AssistantV2(authenticator={my_authenticator}) service.my_service_call(headers={'X-Global-Transaction-Id': ''}) ``` @@ -436,7 +436,7 @@ If your service instance is of CP4D, below are two ways of initializing the assi The SDK will manage the token for the user ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator authenticator = CloudPakForDataAuthenticator( @@ -445,7 +445,7 @@ authenticator = CloudPakForDataAuthenticator( '', # should be of the form https://{icp_cluster_host}{instance-id}/api disable_ssl_verification=True) # Disable ssl verification for authenticator -assistant = AssistantV1( +assistant = AssistantV2( version='', authenticator=authenticator) assistant.set_service_url('') # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api @@ -455,11 +455,11 @@ assistant.set_disable_ssl_verification(True) # MAKE SURE SSL VERIFICATION IS DIS ### 2) Supplying the access token ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator authenticator = BearerTokenAuthenticator('your managed access token') -assistant = AssistantV1(version='', +assistant = AssistantV2(version='', authenticator=authenticator) assistant.set_service_url('') # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api assistant.set_disable_ssl_verification(True) # MAKE SURE SSL VERIFICATION IS DISABLED From 780fe03656d5fda0ab1a1c5a3bac572507b9cfcb Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 17 Oct 2024 10:25:03 -0500 Subject: [PATCH 02/11] feat(stt): readd interimResults and lowLatency wss params --- examples/microphone-speech-to-text.py | 3 +- ibm_watson/speech_to_text_v1_adapter.py | 22 +++++++- ibm_watson/websocket/recognize_listener.py | 19 +++---- test/integration/test_speech_to_text_v1.py | 60 ++++++++++++++++++++++ 4 files changed, 93 insertions(+), 11 deletions(-) diff --git a/examples/microphone-speech-to-text.py b/examples/microphone-speech-to-text.py index fb0fbd1a..9174de74 100644 --- a/examples/microphone-speech-to-text.py +++ b/examples/microphone-speech-to-text.py @@ -72,7 +72,8 @@ def recognize_using_weboscket(*args): mycallback = MyRecognizeCallback() speech_to_text.recognize_using_websocket(audio=audio_source, content_type='audio/l16; rate=44100', - recognize_callback=mycallback) + recognize_callback=mycallback, + interim_results=True) ############################################### #### Prepare the for recording using Pyaudio ## diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 67820be8..dabe6526 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -33,6 +33,7 @@ def recognize_using_websocket(self, customization_weight=None, base_model_version=None, inactivity_timeout=None, + interim_results=None, keywords=None, keywords_threshold=None, max_alternatives=None, @@ -54,6 +55,7 @@ def recognize_using_websocket(self, split_transcript_at_phrase_end=None, speech_detector_sensitivity=None, background_audio_suppression=None, + low_latency=None, character_insertion_bias=None, **kwargs): """ @@ -269,6 +271,22 @@ def recognize_using_websocket(self, * 1.0 suppresses all audio (no audio is transcribed). The values increase on a monotonic curve. See [Background audio suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression). + :param bool low_latency: (optional) If `true` for next-generation + `Multimedia` and `Telephony` models that support low latency, directs the + service to produce results even more quickly than it usually does. + Next-generation models produce transcription results faster than + previous-generation models. The `low_latency` parameter causes the models + to produce results even more quickly, though the results might be less + accurate when the parameter is used. + **Note:** The parameter is beta functionality. It is not available for + previous-generation `Broadband` and `Narrowband` models. It is available + only for some next-generation models. + * For a list of next-generation models that support low latency, see + [Supported language + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported) + for next-generation models. + * For more information about the `low_latency` parameter, see [Low + latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). :param float character_insertion_bias: (optional) For next-generation `Multimedia` and `Telephony` models, an indication of whether the service is biased to recognize shorter or longer strings of characters when @@ -337,6 +355,7 @@ def recognize_using_websocket(self, 'customization_weight': customization_weight, 'content_type': content_type, 'inactivity_timeout': inactivity_timeout, + 'interim_results': interim_results, 'keywords': keywords, 'keywords_threshold': keywords_threshold, 'max_alternatives': max_alternatives, @@ -356,7 +375,8 @@ def recognize_using_websocket(self, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, - 'character_insertion_bias': character_insertion_bias + 'character_insertion_bias': character_insertion_bias, + 'low_latency': low_latency, } options = {k: v for k, v in options.items() if v is not None} request['options'] = options diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index 041bcf69..43eb7961 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -196,15 +196,16 @@ def on_data(self, ws, message, message_type, fin): # set of transcriptions and send them to the appropriate callbacks. results = json_object.get('results') if results: - b_final = (results[0].get('final') is True) - alternatives = results[0].get('alternatives') - if alternatives: - hypothesis = alternatives[0].get('transcript') - transcripts = self.extract_transcripts(alternatives) - if b_final: - self.callback.on_transcription(transcripts) - if hypothesis: - self.callback.on_hypothesis(hypothesis) + if (self.options.get('interim_results') is True): + b_final = (results[0].get('final') is True) + alternatives = results[0].get('alternatives') + if alternatives: + hypothesis = alternatives[0].get('transcript') + transcripts = self.extract_transcripts(alternatives) + if b_final: + self.callback.on_transcription(transcripts) + if hypothesis: + self.callback.on_hypothesis(hypothesis) else: final_transcript = [] for result in results: diff --git a/test/integration/test_speech_to_text_v1.py b/test/integration/test_speech_to_text_v1.py index 1d41df96..4defbea1 100644 --- a/test/integration/test_speech_to_text_v1.py +++ b/test/integration/test_speech_to_text_v1.py @@ -118,6 +118,66 @@ def on_data(self, data): assert test_callback.data['results'][0]['alternatives'][0] ['transcript'] == 'thunderstorms could produce large hail isolated tornadoes and heavy rain ' + def test_on_transcription_interim_results_false(self): + class MyRecognizeCallback(RecognizeCallback): + def __init__(self): + RecognizeCallback.__init__(self) + self.error = None + self.transcript = None + def on_error(self, error): + self.error = error + def on_transcription(self, transcript): + self.transcript = transcript + test_callback = MyRecognizeCallback() + with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: + audio_source = AudioSource(audio_file, False) + self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", + interim_results=False, low_latency=False) + assert test_callback.error is None + assert test_callback.transcript is not None + assert test_callback.transcript[0][0]['transcript'] in ['isolated tornadoes ', 'isolated tornados '] + assert test_callback.transcript[1][0]['transcript'] == 'and heavy rain ' + def test_on_transcription_interim_results_true(self): + class MyRecognizeCallback(RecognizeCallback): + def __init__(self): + RecognizeCallback.__init__(self) + self.error = None + self.transcript = None + def on_error(self, error): + self.error = error + def on_transcription(self, transcript): + self.transcript = transcript + assert transcript[0]['confidence'] is not None + assert transcript[0]['transcript'] is not None + test_callback = MyRecognizeCallback() + with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: + audio_source = AudioSource(audio_file, False) + self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", + interim_results=True, low_latency=True) + assert test_callback.error is None + assert test_callback.transcript is not None + assert test_callback.transcript[0]['transcript'] == 'and heavy rain ' + def test_on_transcription_interim_results_true_low_latency_false(self): + class MyRecognizeCallback(RecognizeCallback): + def __init__(self): + RecognizeCallback.__init__(self) + self.error = None + self.transcript = None + def on_error(self, error): + self.error = error + def on_transcription(self, transcript): + self.transcript = transcript + assert transcript[0]['confidence'] is not None + assert transcript[0]['transcript'] is not None + test_callback = MyRecognizeCallback() + with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: + audio_source = AudioSource(audio_file, False) + self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", + interim_results=True, low_latency=False) + assert test_callback.error is None + assert test_callback.transcript is not None + assert test_callback.transcript[0]['transcript'] == 'and heavy rain ' + def test_custom_grammars(self): customization_id = None for custom_model in self.custom_models.get('customizations'): From 8411104df1149e34ebf42e69a2d330bd4fdb9fc3 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 17 Oct 2024 10:26:03 -0500 Subject: [PATCH 03/11] feat(stt): add new speech models --- ibm_watson/speech_to_text_v1.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 0ad6d376..b0831533 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -4332,19 +4332,25 @@ class ModelId(str, Enum): EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' + ES_AR = 'es-AR' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL = 'es-CL' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO = 'es-CO' ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES = 'es-ES' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' ES_LA_TELEPHONY = 'es-LA_Telephony' + ES_MX = 'es-MX' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE = 'es-PE' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA = 'fr-CA' @@ -4376,6 +4382,7 @@ class ModelId(str, Enum): NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' + PT_BR = 'pt-BR' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' @@ -4454,19 +4461,25 @@ class Model(str, Enum): EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' + ES_AR = 'es-AR' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL = 'es-CL' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO = 'es-CO' ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES = 'es-ES' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' ES_LA_TELEPHONY = 'es-LA_Telephony' + ES_MX = 'es-MX' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE = 'es-PE' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA = 'fr-CA' @@ -4498,6 +4511,7 @@ class Model(str, Enum): NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' + PT_BR = 'pt-BR' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' @@ -4576,19 +4590,25 @@ class Model(str, Enum): EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' + ES_AR = 'es-AR' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL = 'es-CL' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO = 'es-CO' ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES = 'es-ES' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' ES_LA_TELEPHONY = 'es-LA_Telephony' + ES_MX = 'es-MX' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE = 'es-PE' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA = 'fr-CA' @@ -4620,6 +4640,7 @@ class Model(str, Enum): NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' + PT_BR = 'pt-BR' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' From 8651121fdd02d6095e8923302982bdc1f656ed8e Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 17 Oct 2024 11:26:07 -0500 Subject: [PATCH 04/11] fix(nlu): remove summarization param BREAKING CHANGE: change training_data_content_type default to None --- .../natural_language_understanding_v1.py | 96 +------------------ .../test_natural_language_understanding_v1.py | 44 --------- 2 files changed, 4 insertions(+), 136 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 967e52c0..d56cb364 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -24,15 +24,6 @@ models](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) with Watson Knowledge Studio to detect custom entities and relations in Natural Language Understanding. -IBM is sunsetting Watson Natural Language Understanding Custom Sentiment (BETA). From -**June 3, 2023** onward, you will no longer be able to use the Custom Sentiment -feature.

To ensure we continue providing our clients with robust and powerful -text classification capabilities, IBM recently announced the general availability of a new -[single-label text classification -capability](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-classifications). -This new feature includes extended language support and training data customizations -suited for building a custom sentiment classifier.

If you would like more -information or further guidance, please contact IBM Cloud Support.{: deprecated} API Version: 1.0 See: https://cloud.ibm.com/docs/natural-language-understanding @@ -122,7 +113,6 @@ def analyze( - Semantic roles - Sentiment - Syntax - - Summarization (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/natural-language-understanding?topic=natural-language-understanding-detectable-languages). @@ -312,7 +302,7 @@ def create_categories_model( language: str, training_data: BinaryIO, *, - training_data_content_type: Optional[str] = 'application/json', + training_data_content_type: Optional[str] = None, name: Optional[str] = None, user_metadata: Optional[dict] = None, description: Optional[str] = None, @@ -499,7 +489,7 @@ def update_categories_model( language: str, training_data: BinaryIO, *, - training_data_content_type: Optional[str] = 'application/json', + training_data_content_type: Optional[str] = None, name: Optional[str] = None, user_metadata: Optional[dict] = None, description: Optional[str] = None, @@ -653,7 +643,7 @@ def create_classifications_model( language: str, training_data: BinaryIO, *, - training_data_content_type: Optional[str] = 'application/json', + training_data_content_type: Optional[str] = None, name: Optional[str] = None, user_metadata: Optional[dict] = None, description: Optional[str] = None, @@ -849,7 +839,7 @@ def update_classifications_model( language: str, training_data: BinaryIO, *, - training_data_content_type: Optional[str] = 'application/json', + training_data_content_type: Optional[str] = None, name: Optional[str] = None, user_metadata: Optional[dict] = None, description: Optional[str] = None, @@ -3632,10 +3622,6 @@ class Features: `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :param SummarizationOptions summarization: (optional) (Experimental) Returns a - summary of content. - Supported languages: English only. - Supported regions: Dallas region only. :param CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, @@ -3656,7 +3642,6 @@ def __init__( relations: Optional['RelationsOptions'] = None, semantic_roles: Optional['SemanticRolesOptions'] = None, sentiment: Optional['SentimentOptions'] = None, - summarization: Optional['SummarizationOptions'] = None, categories: Optional['CategoriesOptions'] = None, syntax: Optional['SyntaxOptions'] = None, ) -> None: @@ -3707,10 +3692,6 @@ def __init__( and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :param SummarizationOptions summarization: (optional) (Experimental) - Returns a summary of content. - Supported languages: English only. - Supported regions: Dallas region only. :param CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, @@ -3727,7 +3708,6 @@ def __init__( self.relations = relations self.semantic_roles = semantic_roles self.sentiment = sentiment - self.summarization = summarization self.categories = categories self.syntax = syntax @@ -3755,9 +3735,6 @@ def from_dict(cls, _dict: Dict) -> 'Features': semantic_roles) if (sentiment := _dict.get('sentiment')) is not None: args['sentiment'] = SentimentOptions.from_dict(sentiment) - if (summarization := _dict.get('summarization')) is not None: - args['summarization'] = SummarizationOptions.from_dict( - summarization) if (categories := _dict.get('categories')) is not None: args['categories'] = CategoriesOptions.from_dict(categories) if (syntax := _dict.get('syntax')) is not None: @@ -3815,11 +3792,6 @@ def to_dict(self) -> Dict: _dict['sentiment'] = self.sentiment else: _dict['sentiment'] = self.sentiment.to_dict() - if hasattr(self, 'summarization') and self.summarization is not None: - if isinstance(self.summarization, dict): - _dict['summarization'] = self.summarization - else: - _dict['summarization'] = self.summarization.to_dict() if hasattr(self, 'categories') and self.categories is not None: if isinstance(self.categories, dict): _dict['categories'] = self.categories @@ -5619,66 +5591,6 @@ def __ne__(self, other: 'SentimentResult') -> bool: return not self == other -class SummarizationOptions: - """ - (Experimental) Returns a summary of content. - Supported languages: English only. - Supported regions: Dallas region only. - - :param int limit: (optional) Maximum number of summary sentences to return. - """ - - def __init__( - self, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a SummarizationOptions object. - - :param int limit: (optional) Maximum number of summary sentences to return. - """ - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SummarizationOptions': - """Initialize a SummarizationOptions object from a json dictionary.""" - args = {} - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SummarizationOptions object from 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 _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this SummarizationOptions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SummarizationOptions') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SummarizationOptions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class SyntaxOptions: """ Returns tokens and sentences from the input text. diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index b79c21c4..86e529fc 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -136,10 +136,6 @@ def test_analyze_all_params(self): sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - # Construct a dict representation of a SummarizationOptions model - summarization_options_model = {} - summarization_options_model['limit'] = 3 - # Construct a dict representation of a CategoriesOptions model categories_options_model = {} categories_options_model['explanation'] = False @@ -167,7 +163,6 @@ def test_analyze_all_params(self): features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model - features_model['summarization'] = summarization_options_model features_model['categories'] = categories_options_model features_model['syntax'] = syntax_options_model @@ -281,10 +276,6 @@ def test_analyze_value_error(self): sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - # Construct a dict representation of a SummarizationOptions model - summarization_options_model = {} - summarization_options_model['limit'] = 3 - # Construct a dict representation of a CategoriesOptions model categories_options_model = {} categories_options_model['explanation'] = False @@ -312,7 +303,6 @@ def test_analyze_value_error(self): features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model - features_model['summarization'] = summarization_options_model features_model['categories'] = categories_options_model features_model['syntax'] = syntax_options_model @@ -2787,9 +2777,6 @@ def test_features_serialization(self): sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - summarization_options_model = {} # SummarizationOptions - summarization_options_model['limit'] = 3 - categories_options_model = {} # CategoriesOptions categories_options_model['explanation'] = False categories_options_model['limit'] = 3 @@ -2814,7 +2801,6 @@ def test_features_serialization(self): features_model_json['relations'] = relations_options_model features_model_json['semantic_roles'] = semantic_roles_options_model features_model_json['sentiment'] = sentiment_options_model - features_model_json['summarization'] = summarization_options_model features_model_json['categories'] = categories_options_model features_model_json['syntax'] = syntax_options_model @@ -3639,36 +3625,6 @@ def test_sentiment_result_serialization(self): assert sentiment_result_model_json2 == sentiment_result_model_json -class TestModel_SummarizationOptions: - """ - Test Class for SummarizationOptions - """ - - def test_summarization_options_serialization(self): - """ - Test serialization/deserialization for SummarizationOptions - """ - - # Construct a json representation of a SummarizationOptions model - summarization_options_model_json = {} - summarization_options_model_json['limit'] = 3 - - # Construct a model instance of SummarizationOptions by calling from_dict on the json representation - summarization_options_model = SummarizationOptions.from_dict(summarization_options_model_json) - assert summarization_options_model != False - - # Construct a model instance of SummarizationOptions by calling from_dict on the json representation - summarization_options_model_dict = SummarizationOptions.from_dict(summarization_options_model_json).__dict__ - summarization_options_model2 = SummarizationOptions(**summarization_options_model_dict) - - # Verify the model instances are equivalent - assert summarization_options_model == summarization_options_model2 - - # Convert model instance back to dict and verify no loss of data - summarization_options_model_json2 = summarization_options_model.to_dict() - assert summarization_options_model_json2 == summarization_options_model_json - - class TestModel_SyntaxOptions: """ Test Class for SyntaxOptions From 6ba9562c567f369d5f1f66b7f050fd203b5ca286 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 17 Oct 2024 12:08:06 -0500 Subject: [PATCH 05/11] feat(discov1): remove discoV1 BREAKING CHANGE: DiscoveryV1 functionality has been removed --- .github/workflows/integration-test.yml | 6 - examples/discovery_v1.py | 65 - ibm_watson/__init__.py | 1 - ibm_watson/discovery_v1.py | 15128 ----------------------- test/integration/test_discovery_v1.py | 292 - test/unit/test_discovery_v1.py | 12080 ------------------ 6 files changed, 27572 deletions(-) delete mode 100644 examples/discovery_v1.py delete mode 100644 ibm_watson/discovery_v1.py delete mode 100644 test/integration/test_discovery_v1.py delete mode 100644 test/unit/test_discovery_v1.py diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index 05e66e57..4f55f471 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -47,18 +47,12 @@ jobs: ASSISTANT_WORKSPACE_ID: ${{ secrets.WA_WORKSPACE_ID }} ASSISTANT_ASSISTANT_ID: ${{ secrets.WA_ASSISTANT_ID }} ASSISTANT_URL: "https://api.us-south.assistant.watson.cloud.ibm.com" - DISCOVERY_APIKEY: ${{ secrets.D1_APIKEY }} - DISCOVERY_ENVIRONMENT_ID: ${{ secrets.D1_ENVIRONMENT_ID }} - DISCOVERY_COLLECTION_ID: ${{ secrets.D1_COLLECTION_ID }} - DISCOVERY_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" DISCOVERY_V2_APIKEY: ${{ secrets.D2_APIKEY }} DISCOVERY_V2_PROJECT_ID: ${{ secrets.D2_PROJECT_ID }} DISCOVERY_V2_COLLECTION_ID: ${{ secrets.D2_COLLECTION_ID }} DISCOVERY_V2_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" run: | pip3 install -U python-dotenv - pytest test/integration/test_assistant_v1.py -rap - pytest test/integration/test_discovery_v1.py -rap pytest test/integration/test_discovery_v2.py -rap pytest test/integration/test_language_translator_v3.py -rap pytest test/integration/test_natural_language_understanding_v1.py -rap diff --git a/examples/discovery_v1.py b/examples/discovery_v1.py deleted file mode 100644 index 4f32acf2..00000000 --- a/examples/discovery_v1.py +++ /dev/null @@ -1,65 +0,0 @@ -import json -from ibm_watson import DiscoveryV1 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your_api_key') -discovery = DiscoveryV1( - version='2018-08-01', - authenticator=authenticator) -discovery.set_service_url('https://api.us-south.discovery.watson.cloud.ibm.com') - -environments = discovery.list_environments().get_result() -print(json.dumps(environments, indent=2)) - -news_environment_id = 'system' -print(json.dumps(news_environment_id, indent=2)) - -collections = discovery.list_collections(news_environment_id).get_result() -news_collections = [x for x in collections['collections']] -print(json.dumps(collections, indent=2)) - -configurations = discovery.list_configurations( - environment_id=news_environment_id).get_result() -print(json.dumps(configurations, indent=2)) - -query_results = discovery.query( - news_environment_id, - news_collections[0]['collection_id'], - filter='extracted_metadata.sha1::f5*', - return_fields='extracted_metadata.sha1').get_result() -print(json.dumps(query_results, indent=2)) - -# new_environment = discovery.create_environment(name="new env", description="bogus env").get_result() -# print(new_environment) - -# environment = discovery.get_environment(environment_id=new_environment['environment_id']).get_result() -# if environment['status'] == 'active': -# writable_environment_id = new_environment['environment_id'] -# new_collection = discovery.create_collection(environment_id=writable_environment_id, -# name='Example Collection', -# description="just a test").get_result() - -# print(new_collection) - -# collections = discovery.list_collections(environment_id=writable_environment_id).get_result() -# print(collections) - -# res = discovery.delete_collection(environment_id='', -# collection_id=new_collection['collection_id']).get_result() -# print(res) - -# collections = discovery.list_collections(environment_id=writable_environment_id).get_result() -# print(collections) - -# with open(os.path.join(os.getcwd(), '..','resources', 'simple.html')) as fileinfo: -# res = discovery.add_document(environment_id=writable_environment_id, -# collection_id=collections['collections'][0]['collection_id'], -# file=fileinfo).get_result() -# print(res) - -# res = discovery.get_collection(environment_id=writable_environment_id, -# collection_id=collections['collections'][0]['collection_id']).get_result() -# print(res['document_counts']) - -#res = discovery.delete_environment(environment_id=writable_environment_id).get_result() -#print(res) diff --git a/ibm_watson/__init__.py b/ibm_watson/__init__.py index aed80a79..12ace99e 100755 --- a/ibm_watson/__init__.py +++ b/ibm_watson/__init__.py @@ -20,7 +20,6 @@ from .language_translator_v3 import LanguageTranslatorV3 from .natural_language_understanding_v1 import NaturalLanguageUnderstandingV1 from .text_to_speech_v1 import TextToSpeechV1 -from .discovery_v1 import DiscoveryV1 from .discovery_v2 import DiscoveryV2 from .version import __version__ from .common import get_sdk_headers diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py deleted file mode 100644 index a604775e..00000000 --- a/ibm_watson/discovery_v1.py +++ /dev/null @@ -1,15128 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2019, 2024. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# 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. - -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 -""" -IBM Watson™ Discovery v1 is a cognitive search and content analytics engine that you -can add to applications to identify patterns, trends and actionable insights to drive -better decision-making. Securely unify structured and unstructured data with pre-enriched -content, and use a simplified query language to eliminate the need for manual filtering of -results. - -API Version: 1.0 -See: https://cloud.ibm.com/docs/discovery -""" - -from datetime import date -from datetime import datetime -from enum import Enum -from os.path import basename -from typing import BinaryIO, Dict, List, Optional -import json -import sys - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import convert_list, convert_model, date_to_string, datetime_to_string, string_to_date, string_to_datetime - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class DiscoveryV1(BaseService): - """The Discovery V1 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.discovery.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'discovery' - - def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Discovery service. - - :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2019-04-30`. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md - about initializing the authenticator of your choice. - """ - if version is None: - raise ValueError('version must be provided') - - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.version = version - self.configure_service(service_name) - - ######################### - # Environments - ######################### - - def create_environment( - self, - name: str, - *, - description: Optional[str] = None, - size: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create an environment. - - Creates a new environment for private data. An environment must be created before - collections can be created. - **Note**: You can create only one environment for private data per service - instance. An attempt to create another environment results in an error. - - :param str name: Name that identifies the environment. - :param str description: (optional) Description of the environment. - :param str size: (optional) Size of the environment. In the Lite plan the - default and only accepted value is `LT`, in all other plans the default is - `S`. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Environment` object - """ - - if name is None: - raise ValueError('name must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_environment', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'size': size, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/environments' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def list_environments( - self, - *, - name: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - List environments. - - List existing environments for the service instance. - - :param str name: (optional) Show only the environment with the given name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListEnvironmentsResponse` object - """ - - headers = {} - 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, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/environments' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_environment( - self, - environment_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get environment info. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Environment` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_environment', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_environment( - self, - environment_id: str, - *, - name: Optional[str] = None, - description: Optional[str] = None, - size: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Update an environment. - - Updates an environment. The environment's **name** and **description** parameters - can be changed. You must specify a **name** for the environment. - - :param str environment_id: The ID of the environment. - :param str name: (optional) Name that identifies the environment. - :param str description: (optional) Description of the environment. - :param str size: (optional) Size to change the environment to. **Note:** - Lite plan users cannot change the environment size. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Environment` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_environment', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'size': size, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_environment( - self, - environment_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete environment. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteEnvironmentResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_environment', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def list_fields( - self, - environment_id: str, - collection_ids: List[str], - **kwargs, - ) -> DetailedResponse: - """ - List fields across collections. - - Gets a list of the unique fields (and their types) stored in the indexes of the - specified collections. - - :param str environment_id: The ID of the environment. - :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. - :rtype: DetailedResponse with `dict` result representing a `ListCollectionFieldsResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if collection_ids is None: - raise ValueError('collection_ids must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_fields', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'collection_ids': convert_list(collection_ids), - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/fields'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Configurations - ######################### - - def create_configuration( - self, - environment_id: str, - name: str, - *, - description: Optional[str] = None, - conversions: Optional['Conversions'] = None, - enrichments: Optional[List['Enrichment']] = None, - normalizations: Optional[List['NormalizationOperation']] = None, - source: Optional['Source'] = None, - **kwargs, - ) -> DetailedResponse: - """ - Add configuration. - - Creates a new configuration. - If the input configuration contains the **configuration_id**, **created**, or - **updated** properties, then they are ignored and overridden by the system, and an - error is not returned so that the overridden fields do not need to be removed when - copying a configuration. - The configuration can contain unrecognized JSON fields. Any such fields are - ignored and do not generate an error. This makes it easier to use newer - configuration files with older versions of the API and the service. It also makes - it possible for the tooling to add additional metadata and information to the - configuration. - - :param str environment_id: The ID of the environment. - :param str name: The name of the configuration. - :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 - enrichment settings for the configuration. - :param List[NormalizationOperation] normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a - normalized form. Operations are executed in the order that they appear in - the array. - :param Source source: (optional) Object containing source parameters for - the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Configuration` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if name is None: - raise ValueError('name must be provided') - if conversions is not None: - conversions = convert_model(conversions) - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] - if normalizations is not None: - normalizations = [convert_model(x) for x in normalizations] - if source is not None: - source = convert_model(source) - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_configuration', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'conversions': conversions, - 'enrichments': enrichments, - 'normalizations': normalizations, - 'source': source, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def list_configurations( - self, - environment_id: str, - *, - name: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - List configurations. - - Lists existing configurations for the service instance. - - :param str environment_id: The ID of the environment. - :param str name: (optional) Find configurations with the given name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListConfigurationsResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_configurations', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'name': name, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_configuration( - self, - environment_id: str, - configuration_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get configuration details. - - :param str environment_id: The ID of the environment. - :param str configuration_id: The ID of the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Configuration` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not configuration_id: - raise ValueError('configuration_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_configuration', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'configuration_id'] - path_param_values = self.encode_path_vars(environment_id, - configuration_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_configuration( - self, - environment_id: str, - configuration_id: str, - name: str, - *, - description: Optional[str] = None, - conversions: Optional['Conversions'] = None, - enrichments: Optional[List['Enrichment']] = None, - normalizations: Optional[List['NormalizationOperation']] = None, - source: Optional['Source'] = None, - **kwargs, - ) -> DetailedResponse: - """ - Update a configuration. - - Replaces an existing configuration. - * Completely replaces the original configuration. - * The **configuration_id**, **updated**, and **created** fields are accepted in - the request, but they are ignored, and an error is not generated. It is also - acceptable for users to submit an updated configuration with none of the three - properties. - * Documents are processed with a snapshot of the configuration as it was at the - time the document was submitted to be ingested. This means that already submitted - documents will not see any updates made to the configuration. - - :param str environment_id: The ID of the environment. - :param str configuration_id: The ID of the configuration. - :param str name: The name of the configuration. - :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 - enrichment settings for the configuration. - :param List[NormalizationOperation] normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a - normalized form. Operations are executed in the order that they appear in - the array. - :param Source source: (optional) Object containing source parameters for - the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Configuration` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not configuration_id: - raise ValueError('configuration_id must be provided') - if name is None: - raise ValueError('name must be provided') - if conversions is not None: - conversions = convert_model(conversions) - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] - if normalizations is not None: - normalizations = [convert_model(x) for x in normalizations] - if source is not None: - source = convert_model(source) - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_configuration', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'conversions': conversions, - 'enrichments': enrichments, - 'normalizations': normalizations, - 'source': source, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'configuration_id'] - path_param_values = self.encode_path_vars(environment_id, - configuration_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_configuration( - self, - environment_id: str, - configuration_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete a configuration. - - The deletion is performed unconditionally. A configuration deletion request - succeeds even if the configuration is referenced by a collection or document - ingestion. However, documents that have already been submitted for processing - continue to use the deleted configuration. Documents are always processed with a - snapshot of the configuration as it existed at the time the document was - submitted. - - :param str environment_id: The ID of the environment. - :param str configuration_id: The ID of the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteConfigurationResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not configuration_id: - raise ValueError('configuration_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_configuration', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'configuration_id'] - path_param_values = self.encode_path_vars(environment_id, - configuration_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Collections - ######################### - - def create_collection( - self, - environment_id: str, - name: str, - *, - description: Optional[str] = None, - configuration_id: Optional[str] = None, - language: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create a collection. - - :param str environment_id: The ID of the environment. - :param str name: The name of the collection to be created. - :param str description: (optional) A description of the collection. - :param str configuration_id: (optional) The ID of the configuration in - which the collection is to be created. - :param str language: (optional) The language of the documents stored in the - collection, in the form of an ISO 639-1 language code. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Collection` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if name is None: - raise ValueError('name must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_collection', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'configuration_id': configuration_id, - 'language': language, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def list_collections( - self, - environment_id: str, - *, - name: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - List collections. - - Lists existing collections for the service instance. - - :param str environment_id: The ID of the environment. - :param str name: (optional) Find collections with the given name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_collections', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'name': name, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_collection( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get collection details. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Collection` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_collection', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_collection( - self, - environment_id: str, - collection_id: str, - name: str, - *, - description: Optional[str] = None, - configuration_id: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Update a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str name: The name of the collection. - :param str description: (optional) A description of the collection. - :param str configuration_id: (optional) The ID of the configuration in - which the collection is to be updated. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Collection` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if name is None: - raise ValueError('name must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_collection', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'configuration_id': configuration_id, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_collection( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteCollectionResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_collection', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def list_collection_fields( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List collection fields. - - Gets a list of the unique fields (and their types) stored in the index. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListCollectionFieldsResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_collection_fields', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/fields'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Query modifications - ######################### - - def list_expansions( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get the expansion list. - - Returns the current expansion list for the specified collection. If an expansion - list is not specified, an object with empty expansion arrays is returned. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Expansions` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_expansions', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_expansions( - self, - environment_id: str, - collection_id: str, - expansions: List['Expansion'], - **kwargs, - ) -> DetailedResponse: - """ - Create or update expansion list. - - Create or replace the Expansion list for this collection. The maximum number of - expanded terms per collection is `500`. The current expansion list is replaced - with the uploaded content. - - :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. - 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 to all other terms in the object. Unidirectional means - that a set list of terms can be expanded into a second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. - When found in a query, all items in the **expanded_terms** array are then - expanded to the other items in the same array. - To create a uni-directional expansion, specify both an array of - **input_terms** and an array of **expanded_terms**. When items in the - **input_terms** array are present in a query, they are expanded using the - items listed in the **expanded_terms** array. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Expansions` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if expansions is None: - raise ValueError('expansions must be provided') - expansions = [convert_model(x) for x in expansions] - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_expansions', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'expansions': expansions, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_expansions( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete the expansion list. - - Remove the expansion information for this collection. The expansion list must be - deleted to disable query expansion for a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_expansions', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_tokenization_dictionary_status( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get tokenization dictionary status. - - Returns the current status of the tokenization dictionary for the specified - collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_tokenization_dictionary_status', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_tokenization_dictionary( - self, - environment_id: str, - collection_id: str, - *, - tokenization_rules: Optional[List['TokenDictRule']] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create tokenization dictionary. - - Upload a custom tokenization dictionary to use with the specified collection. - - :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 - 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. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if tokenization_rules is not None: - tokenization_rules = [convert_model(x) for x in tokenization_rules] - headers = {} - 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, - } - - data = { - 'tokenization_rules': tokenization_rules, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_tokenization_dictionary( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete tokenization dictionary. - - Delete the tokenization dictionary from the collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_tokenization_dictionary', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_stopword_list_status( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get stopword list status. - - Returns the current status of the stopword list for the specified collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_stopword_list_status', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_stopword_list( - self, - environment_id: str, - collection_id: str, - stopword_file: BinaryIO, - *, - stopword_filename: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create stopword list. - - Upload a custom stopword list to use with the specified collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param BinaryIO 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. - :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if stopword_file is None: - raise ValueError('stopword_file must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_stopword_list', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - form_data = [] - if not stopword_filename and hasattr(stopword_file, 'name'): - stopword_filename = basename(stopword_file.name) - if not stopword_filename: - raise ValueError('stopword_filename must be provided') - form_data.append(('stopword_file', (stopword_filename, stopword_file, - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_stopword_list( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete a custom stopword list. - - Delete a custom stopword list from the collection. After a custom stopword list is - deleted, the default list is used for the collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_stopword_list', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Documents - ######################### - - def add_document( - self, - environment_id: str, - collection_id: str, - *, - file: Optional[BinaryIO] = None, - filename: Optional[str] = None, - file_content_type: Optional[str] = None, - metadata: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Add a document. - - Add a document to a collection with optional metadata. - * The **version** query parameter is still required. - * Returns immediately after the system has accepted the document for processing. - * The user must provide document content, metadata, or both. If the request is - missing both document content and metadata, it is rejected. - * The user can set the **Content-Type** parameter on the **file** part to - indicate the media type of the document. If the **Content-Type** parameter is - missing or is one of the generic media types (for example, - `application/octet-stream`), then the service attempts to automatically detect the - document's media type. - * The following field names are reserved and will be filtered out if present - after normalization: `id`, `score`, `highlight`, and any field with the prefix of: - `_`, `+`, or `-` - * Fields with empty name values after normalization are filtered out before - indexing. - * Fields containing the following characters after normalization are filtered - out before indexing: `#` and `,` - **Note:** Documents can be added with a specific **document_id** by using the - **/v1/environments/{environment_id}/collections/{collection_id}/documents** - method. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param BinaryIO 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. - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_document', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - form_data = [] - if file: - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if metadata: - form_data.append(('metadata', (None, metadata, 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - ) - - response = self.send(request, **kwargs) - return response - - def get_document_status( - self, - environment_id: str, - collection_id: str, - document_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get document details. - - Fetch status details about a submitted document. **Note:** this operation does not - return the document itself. Instead, it returns only the document's processing - status and any notices (warnings or errors) that were generated when the document - was ingested. Use the query API to retrieve the actual document content. - - :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 dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not document_id: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_document_status', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'document_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_document( - self, - environment_id: str, - collection_id: str, - document_id: str, - *, - file: Optional[BinaryIO] = None, - filename: Optional[str] = None, - file_content_type: Optional[str] = None, - metadata: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Update a document. - - Replace an existing document or add a document with a specified **document_id**. - Starts ingesting a document with optional metadata. - **Note:** When uploading a new document with this method it automatically replaces - any document stored with the same **document_id** if it exists. - - :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 BinaryIO 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. - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not document_id: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_document', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - form_data = [] - if file: - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if metadata: - form_data.append(('metadata', (None, metadata, 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'document_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_document( - self, - environment_id: str, - collection_id: str, - document_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete a document. - - If the given document ID is invalid, or if the document is not found, then the a - success response is returned (HTTP status code `200`) with the status set to - 'deleted'. - - :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 dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteDocumentResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not document_id: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_document', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'document_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Queries - ######################### - - def query( - self, - environment_id: str, - collection_id: str, - *, - filter: Optional[str] = None, - query: Optional[str] = None, - natural_language_query: Optional[str] = None, - passages: Optional[bool] = None, - aggregation: Optional[str] = None, - count: Optional[int] = None, - return_: Optional[str] = None, - offset: Optional[int] = None, - sort: Optional[str] = None, - highlight: Optional[bool] = None, - passages_fields: Optional[str] = None, - passages_count: Optional[int] = None, - passages_characters: Optional[int] = None, - deduplicate: Optional[bool] = None, - deduplicate_field: Optional[str] = None, - similar: Optional[bool] = None, - similar_document_ids: Optional[str] = None, - similar_fields: Optional[str] = None, - bias: Optional[str] = None, - spelling_suggestions: Optional[bool] = None, - x_watson_logging_opt_out: Optional[bool] = None, - **kwargs, - ) -> DetailedResponse: - """ - Query a collection. - - By using this method, you can construct long queries. For details, see the - [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts). - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. Use a query search when you want to find the most - relevant search results. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param bool passages: (optional) A passages query that returns the most - relevant passages from the results. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. - :param 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. - :param 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. This parameter - cannot be used in the same query as the **bias** parameter. - :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 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 - return. The search returns fewer passages if the requested total is not - found. The default is `10`. The maximum is `100`. - :param int passages_characters: (optional) The approximate number of - characters that any one passage will have. - :param bool deduplicate: (optional) When `true`, and used with a Watson - Discovery News collection, duplicate results (based on the contents of the - **title** field) are removed. Duplicate comparison is limited to the - current query only; **offset** is not considered. This parameter is - currently Beta functionality. - :param str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :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 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 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 str bias: (optional) Field which the returned results will be biased - against. The specified field must be either a **date** or **number** - format. When a **date** type field is specified returned results are biased - towards field values closer to the current date. When a **number** type - field is specified, returned results are biased towards higher field - values. This parameter cannot be used in the same query as the **sort** - parameter. - :param bool spelling_suggestions: (optional) When `true` and the - **natural_language_query** parameter is used, the **natural_languge_query** - parameter is spell checked. The most likely correction is returned in the - **suggested_query** field of the response (if one exists). - **Important:** this parameter is only valid when using the Cloud Pak - version of Discovery. - :param bool x_watson_logging_opt_out: (optional) If `true`, queries are not - stored in the Discovery **Logs** endpoint. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = { - 'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out, - } - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'passages': passages, - 'aggregation': aggregation, - 'count': count, - 'return': return_, - 'offset': offset, - 'sort': sort, - 'highlight': highlight, - 'passages.fields': passages_fields, - 'passages.count': passages_count, - 'passages.characters': passages_characters, - 'deduplicate': deduplicate, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': similar_document_ids, - 'similar.fields': similar_fields, - 'bias': bias, - 'spelling_suggestions': spelling_suggestions, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/query'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def query_notices( - self, - environment_id: str, - collection_id: str, - *, - filter: Optional[str] = None, - query: Optional[str] = None, - natural_language_query: Optional[str] = None, - passages: Optional[bool] = None, - aggregation: Optional[str] = None, - count: Optional[int] = None, - return_: Optional[List[str]] = None, - offset: Optional[int] = None, - sort: Optional[List[str]] = None, - highlight: Optional[bool] = None, - passages_fields: Optional[List[str]] = None, - passages_count: Optional[int] = None, - passages_characters: Optional[int] = None, - deduplicate_field: Optional[str] = None, - similar: Optional[bool] = None, - similar_document_ids: Optional[List[str]] = None, - similar_fields: Optional[List[str]] = None, - **kwargs, - ) -> DetailedResponse: - """ - Query system notices. - - Queries for notices (errors or warnings) that might have been generated by the - system. Notices are generated when ingesting documents and performing relevance - training. See the [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts) - for more details on the query language. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param bool passages: (optional) A passages query that returns the most - relevant passages from the results. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - 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 - 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 - 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 - 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 - return. The search returns fewer passages if the requested total is not - found. - :param int passages_characters: (optional) The approximate number of - characters that any one passage will have. - :param str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :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 - 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 - 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 - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query_notices', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'passages': passages, - 'aggregation': aggregation, - 'count': count, - 'return': convert_list(return_), - 'offset': offset, - 'sort': convert_list(sort), - 'highlight': highlight, - 'passages.fields': convert_list(passages_fields), - 'passages.count': passages_count, - 'passages.characters': passages_characters, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': convert_list(similar_document_ids), - 'similar.fields': convert_list(similar_fields), - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/notices'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def federated_query( - self, - environment_id: str, - collection_ids: str, - *, - filter: Optional[str] = None, - query: Optional[str] = None, - natural_language_query: Optional[str] = None, - passages: Optional[bool] = None, - aggregation: Optional[str] = None, - count: Optional[int] = None, - return_: Optional[str] = None, - offset: Optional[int] = None, - sort: Optional[str] = None, - highlight: Optional[bool] = None, - passages_fields: Optional[str] = None, - passages_count: Optional[int] = None, - passages_characters: Optional[int] = None, - deduplicate: Optional[bool] = None, - deduplicate_field: Optional[str] = None, - similar: Optional[bool] = None, - similar_document_ids: Optional[str] = None, - similar_fields: Optional[str] = None, - bias: Optional[str] = None, - x_watson_logging_opt_out: Optional[bool] = None, - **kwargs, - ) -> DetailedResponse: - """ - Query multiple collections. - - By using this method, you can construct long queries that search multiple - collection. For details, see the [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts). - - :param str environment_id: The ID of the environment. - :param 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 - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. Use a query search when you want to find the most - relevant search results. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param bool passages: (optional) A passages query that returns the most - relevant passages from the results. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. - :param 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. - :param 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. This parameter - cannot be used in the same query as the **bias** parameter. - :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 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 - return. The search returns fewer passages if the requested total is not - found. The default is `10`. The maximum is `100`. - :param int passages_characters: (optional) The approximate number of - characters that any one passage will have. - :param bool deduplicate: (optional) When `true`, and used with a Watson - Discovery News collection, duplicate results (based on the contents of the - **title** field) are removed. Duplicate comparison is limited to the - current query only; **offset** is not considered. This parameter is - currently Beta functionality. - :param str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :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 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 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 str bias: (optional) Field which the returned results will be biased - against. The specified field must be either a **date** or **number** - format. When a **date** type field is specified returned results are biased - towards field values closer to the current date. When a **number** type - field is specified, returned results are biased towards higher field - values. This parameter cannot be used in the same query as the **sort** - parameter. - :param bool x_watson_logging_opt_out: (optional) If `true`, queries are not - stored in the Discovery **Logs** endpoint. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object - """ - - if not environment_id: - 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, - } - 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, - } - - data = { - 'collection_ids': collection_ids, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'passages': passages, - 'aggregation': aggregation, - 'count': count, - 'return': return_, - 'offset': offset, - 'sort': sort, - 'highlight': highlight, - 'passages.fields': passages_fields, - 'passages.count': passages_count, - 'passages.characters': passages_characters, - 'deduplicate': deduplicate, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': similar_document_ids, - 'similar.fields': similar_fields, - 'bias': bias, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/query'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def federated_query_notices( - self, - environment_id: str, - collection_ids: List[str], - *, - filter: Optional[str] = None, - query: Optional[str] = None, - natural_language_query: Optional[str] = None, - aggregation: Optional[str] = None, - count: Optional[int] = None, - return_: Optional[List[str]] = None, - offset: Optional[int] = None, - sort: Optional[List[str]] = None, - highlight: Optional[bool] = None, - deduplicate_field: Optional[str] = None, - similar: Optional[bool] = None, - similar_document_ids: Optional[List[str]] = None, - similar_fields: Optional[List[str]] = None, - **kwargs, - ) -> DetailedResponse: - """ - Query multiple collection system notices. - - Queries for notices (errors or warnings) that might have been generated by the - system. Notices are generated when ingesting documents and performing relevance - training. See the [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts) - 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 - 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 - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - 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 - 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 - 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 str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :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 - 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 - 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 - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if collection_ids is None: - raise ValueError('collection_ids must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='federated_query_notices', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'collection_ids': convert_list(collection_ids), - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'aggregation': aggregation, - 'count': count, - 'return': convert_list(return_), - 'offset': offset, - 'sort': convert_list(sort), - 'highlight': highlight, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': convert_list(similar_document_ids), - 'similar.fields': convert_list(similar_fields), - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/notices'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_autocompletion( - self, - environment_id: str, - collection_id: str, - prefix: str, - *, - field: Optional[str] = None, - count: Optional[int] = None, - **kwargs, - ) -> DetailedResponse: - """ - Get Autocomplete Suggestions. - - Returns completion query suggestions for the specified prefix. /n/n - **Important:** this method is only valid when using the Cloud Pak version of - Discovery. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str prefix: The prefix to use for autocompletion. For example, the - prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. - :param str field: (optional) The field in the result documents that - autocompletion suggestions are identified from. - :param int count: (optional) The number of autocompletion suggestions to - return. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Completions` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not prefix: - raise ValueError('prefix must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_autocompletion', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'prefix': prefix, - 'field': field, - 'count': count, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/autocompletion'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Training data - ######################### - - def list_training_data( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List training data. - - Lists the training data for the specified collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingDataSet` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_training_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def add_training_data( - self, - environment_id: str, - collection_id: str, - *, - natural_language_query: Optional[str] = None, - filter: Optional[str] = None, - examples: Optional[List['TrainingExample']] = None, - **kwargs, - ) -> DetailedResponse: - """ - Add query to training data. - - Adds a query to the training data for this collection. The query can contain a - filter and natural language query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str natural_language_query: (optional) The natural text query for - 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 - examples. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if examples is not None: - examples = [convert_model(x) for x in examples] - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_training_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'natural_language_query': natural_language_query, - 'filter': filter, - 'examples': examples, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_all_training_data( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete all training data. - - Deletes all training data from a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_all_training_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_training_data( - self, - environment_id: str, - collection_id: str, - query_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get details about a query. - - Gets details for a specific training data query, including the query string and - all examples. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_training_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def delete_training_data( - self, - environment_id: str, - collection_id: str, - query_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete a training data query. - - Removes the training data query and all associated examples from the training data - set. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_training_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def list_training_examples( - self, - environment_id: str, - collection_id: str, - query_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List examples for a training data query. - - List all examples for this training data query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExampleList` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_training_examples', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_training_example( - self, - environment_id: str, - collection_id: str, - query_id: str, - *, - document_id: Optional[str] = None, - cross_reference: Optional[str] = None, - relevance: Optional[int] = None, - **kwargs, - ) -> DetailedResponse: - """ - Add example to training data query. - - Adds a example to this training data query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str document_id: (optional) The document ID associated with this - training example. - :param str cross_reference: (optional) The cross reference associated with - this training example. - :param int relevance: (optional) The relevance of the training example. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_training_example', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'document_id': document_id, - 'cross_reference': cross_reference, - 'relevance': relevance, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_training_example( - self, - environment_id: str, - collection_id: str, - query_id: str, - example_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete example for training data query. - - Deletes the example document with the given ID from the training data query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str example_id: The ID of the document as it is indexed. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - if not example_id: - raise ValueError('example_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_training_example', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = [ - 'environment_id', 'collection_id', 'query_id', 'example_id' - ] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id, example_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_training_example( - self, - environment_id: str, - collection_id: str, - query_id: str, - example_id: str, - *, - cross_reference: Optional[str] = None, - relevance: Optional[int] = None, - **kwargs, - ) -> DetailedResponse: - """ - Change label or cross reference for example. - - Changes the label or cross reference query for this training data example. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str example_id: The ID of the document as it is indexed. - :param str cross_reference: (optional) The example to add. - :param int relevance: (optional) The relevance value for this example. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - if not example_id: - raise ValueError('example_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_training_example', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'cross_reference': cross_reference, - 'relevance': relevance, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = [ - 'environment_id', 'collection_id', 'query_id', 'example_id' - ] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id, example_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def get_training_example( - self, - environment_id: str, - collection_id: str, - query_id: str, - example_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get details for training data example. - - Gets the details for this training example. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str example_id: The ID of the document as it is indexed. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - if not example_id: - raise ValueError('example_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_training_example', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = [ - 'environment_id', 'collection_id', 'query_id', 'example_id' - ] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id, example_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # User data - ######################### - - def delete_user_data( - self, - customer_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete labeled data. - - Deletes all data associated with a specified customer ID. The method has no effect - if no data is associated with the customer ID. - You associate a customer ID with data by passing the **X-Watson-Metadata** header - with a request that passes data. For more information about personal data and - customer IDs, see [Information - security](https://cloud.ibm.com/docs/discovery?topic=discovery-information-security#information-security). - - :param str customer_id: The customer ID for which all data is to be - deleted. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not customer_id: - raise ValueError('customer_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'customer_id': customer_id, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - url = '/v1/user_data' - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Events and feedback - ######################### - - 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 occurred. - - :param str type: The event type to be created. - :param EventData data: Query event data object. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CreateEventResponse` object - """ - - if type is None: - raise ValueError('type must be provided') - if data is None: - raise ValueError('data must be provided') - data = convert_model(data) - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_event', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'type': type, - 'data': data, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/events' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def query_log( - self, - *, - filter: Optional[str] = None, - query: Optional[str] = None, - count: Optional[int] = None, - offset: Optional[int] = None, - sort: Optional[List[str]] = None, - **kwargs, - ) -> DetailedResponse: - """ - Search the query and event log. - - Searches the query and event log to find query sessions that match the specified - criteria. Searching the **logs** endpoint uses the standard Discovery query syntax - for the parameters that are supported. - - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :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 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 - 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 dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `LogQueryResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query_log', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'filter': filter, - 'query': query, - 'count': count, - 'offset': offset, - 'sort': convert_list(sort), - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/logs' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query( - self, - *, - start_time: Optional[datetime] = None, - end_time: Optional[datetime] = None, - result_type: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Number of queries over time. - - Total number of queries using the **natural_language_query** parameter over a - specific time window. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/metrics/number_of_queries' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query_event( - self, - *, - start_time: Optional[datetime] = None, - end_time: Optional[datetime] = None, - result_type: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Number of queries with an event over time. - - Total number of queries using the **natural_language_query** parameter that have a - corresponding "click" event over a specified time window. This metric requires - having integrated event tracking in your application using the **Events** API. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - 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 = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/metrics/number_of_queries_with_event' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query_no_results( - self, - *, - start_time: Optional[datetime] = None, - end_time: Optional[datetime] = None, - result_type: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Number of queries with no search results over time. - - Total number of queries using the **natural_language_query** parameter that have - no results returned over a specified time window. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - 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 = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/metrics/number_of_queries_with_no_search_results' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_metrics_event_rate( - self, - *, - start_time: Optional[datetime] = None, - end_time: Optional[datetime] = None, - result_type: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Percentage of queries with an associated event. - - The percentage of queries using the **natural_language_query** parameter that have - a corresponding "click" event over a specified time window. This metric requires - having integrated event tracking in your application using the **Events** API. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - 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 = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/metrics/event_rate' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query_token_event( - self, - *, - count: Optional[int] = None, - **kwargs, - ) -> DetailedResponse: - """ - Most frequent query tokens with an event. - - The most frequent query tokens parsed from the **natural_language_query** - parameter and their corresponding "click" event rate within the recording period - (queries and events are stored for 30 days). A query token is an individual word - or unigram within the query string. - - :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 dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricTokenResponse` object - """ - - headers = {} - 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, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/metrics/top_query_tokens_with_event_rate' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Credentials - ######################### - - def list_credentials( - self, - environment_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List credentials. - - List all the source credentials that have been created for this service instance. - **Note:** All credentials are sent over an encrypted connection and encrypted at - rest. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CredentialsList` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_credentials', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_credentials( - self, - environment_id: str, - *, - source_type: Optional[str] = None, - credential_details: Optional['CredentialDetails'] = None, - status: Optional['StatusDetails'] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create credentials. - - Creates a set of credentials to connect to a remote source. Created credentials - are used in a configuration to associate a collection with the remote source. - **Note:** All credentials are sent over an encrypted connection and encrypted at - rest. - - :param str environment_id: The ID of the environment. - :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of - Enterprise Box. - - `salesforce` indicates the credentials are used to connect to - Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to - an IBM Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing - details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param StatusDetails status: (optional) Object that contains details about - the status of the authentication process. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Credentials` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if credential_details is not None: - credential_details = convert_model(credential_details) - if status is not None: - status = convert_model(status) - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_credentials', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'source_type': source_type, - 'credential_details': credential_details, - 'status': status, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def get_credentials( - self, - environment_id: str, - credential_id: str, - **kwargs, - ) -> DetailedResponse: - """ - View Credentials. - - Returns details about the specified credentials. - **Note:** Secure credential information such as a password or SSH key is never - returned and must be obtained from the source system. - - :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source - credentials. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Credentials` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not credential_id: - raise ValueError('credential_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_credentials', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'credential_id'] - path_param_values = self.encode_path_vars(environment_id, credential_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_credentials( - self, - environment_id: str, - credential_id: str, - *, - source_type: Optional[str] = None, - credential_details: Optional['CredentialDetails'] = None, - status: Optional['StatusDetails'] = None, - **kwargs, - ) -> DetailedResponse: - """ - Update credentials. - - Updates an existing set of source credentials. - **Note:** All credentials are sent over an encrypted connection and encrypted at - rest. - - :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source - credentials. - :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of - Enterprise Box. - - `salesforce` indicates the credentials are used to connect to - Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to - an IBM Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing - details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param StatusDetails status: (optional) Object that contains details about - the status of the authentication process. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Credentials` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not credential_id: - raise ValueError('credential_id must be provided') - if credential_details is not None: - credential_details = convert_model(credential_details) - if status is not None: - status = convert_model(status) - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_credentials', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'source_type': source_type, - 'credential_details': credential_details, - 'status': status, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'credential_id'] - path_param_values = self.encode_path_vars(environment_id, credential_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_credentials( - self, - environment_id: str, - credential_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete credentials. - - Deletes a set of stored credentials from your Discovery instance. - - :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source - credentials. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteCredentials` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not credential_id: - raise ValueError('credential_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_credentials', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'credential_id'] - path_param_values = self.encode_path_vars(environment_id, credential_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # gatewayConfiguration - ######################### - - def list_gateways( - self, - environment_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List Gateways. - - List the currently configured gateways. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `GatewayList` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_gateways', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_gateway( - self, - environment_id: str, - *, - name: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create Gateway. - - Create a gateway configuration to use with a remotely installed gateway. - - :param str environment_id: The ID of the environment. - :param str name: (optional) User-defined name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Gateway` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_gateway', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def get_gateway( - self, - environment_id: str, - gateway_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List Gateway Details. - - List information about the specified gateway. - - :param str environment_id: The ID of the environment. - :param str gateway_id: The requested gateway ID. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Gateway` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not gateway_id: - raise ValueError('gateway_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_gateway', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'gateway_id'] - path_param_values = self.encode_path_vars(environment_id, gateway_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def delete_gateway( - self, - environment_id: str, - gateway_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete Gateway. - - Delete the specified gateway configuration. - - :param str environment_id: The ID of the environment. - :param str gateway_id: The requested gateway ID. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `GatewayDelete` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not gateway_id: - raise ValueError('gateway_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_gateway', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'gateway_id'] - path_param_values = self.encode_path_vars(environment_id, gateway_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - -class AddDocumentEnums: - """ - Enums for add_document parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' - - -class UpdateDocumentEnums: - """ - Enums for update_document parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' - - -class GetMetricsQueryEnums: - """ - Enums for get_metrics_query parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - - DOCUMENT = 'document' - - -class GetMetricsQueryEventEnums: - """ - Enums for get_metrics_query_event parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - - DOCUMENT = 'document' - - -class GetMetricsQueryNoResultsEnums: - """ - Enums for get_metrics_query_no_results parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - - DOCUMENT = 'document' - - -class GetMetricsEventRateEnums: - """ - Enums for get_metrics_event_rate parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - - DOCUMENT = 'document' - - -############################################################################## -# Models -############################################################################## - - -class Collection: - """ - A collection for storing documents. - - :param str collection_id: (optional) The unique identifier of the collection. - :param str name: (optional) The name of the collection. - :param str description: (optional) The description of the collection. - :param datetime created: (optional) The creation date of the collection in the - format yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. - :param datetime updated: (optional) The timestamp of when the collection was - last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param str status: (optional) The status of the collection. - :param str configuration_id: (optional) The unique identifier of the - collection's configuration. - :param str language: (optional) The language of the documents stored in the - collection. Permitted values include `en` (English), `de` (German), and `es` - (Spanish). - :param DocumentCounts document_counts: (optional) Object containing collection - document count information. - :param CollectionDiskUsage disk_usage: (optional) Summary of the disk usage - statistics for this collection. - :param TrainingStatus training_status: (optional) Training status details. - :param CollectionCrawlStatus crawl_status: (optional) Object containing - information about the crawl status of this collection. - :param SduStatus smart_document_understanding: (optional) Object containing - smart document understanding information for this collection. - """ - - def __init__( - self, - *, - collection_id: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - created: Optional[datetime] = None, - updated: Optional[datetime] = None, - status: Optional[str] = None, - configuration_id: Optional[str] = None, - language: Optional[str] = None, - document_counts: Optional['DocumentCounts'] = None, - disk_usage: Optional['CollectionDiskUsage'] = None, - training_status: Optional['TrainingStatus'] = None, - crawl_status: Optional['CollectionCrawlStatus'] = None, - smart_document_understanding: Optional['SduStatus'] = None, - ) -> None: - """ - Initialize a Collection object. - - :param str name: (optional) The name of the collection. - :param str description: (optional) The description of the collection. - :param str configuration_id: (optional) The unique identifier of the - collection's configuration. - :param str language: (optional) The language of the documents stored in the - collection. Permitted values include `en` (English), `de` (German), and - `es` (Spanish). - :param DocumentCounts document_counts: (optional) Object containing - collection document count information. - :param CollectionDiskUsage disk_usage: (optional) Summary of the disk usage - statistics for this collection. - :param TrainingStatus training_status: (optional) Training status details. - :param CollectionCrawlStatus crawl_status: (optional) Object containing - information about the crawl status of this collection. - :param SduStatus smart_document_understanding: (optional) Object containing - smart document understanding information for this collection. - """ - self.collection_id = collection_id - self.name = name - self.description = description - self.created = created - self.updated = updated - self.status = status - self.configuration_id = configuration_id - self.language = language - self.document_counts = document_counts - self.disk_usage = disk_usage - self.training_status = training_status - self.crawl_status = crawl_status - self.smart_document_understanding = smart_document_understanding - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Collection': - """Initialize a Collection object from a json dictionary.""" - args = {} - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - if (updated := _dict.get('updated')) is not None: - args['updated'] = string_to_datetime(updated) - if (status := _dict.get('status')) is not None: - args['status'] = status - if (configuration_id := _dict.get('configuration_id')) is not None: - args['configuration_id'] = configuration_id - if (language := _dict.get('language')) is not None: - args['language'] = language - if (document_counts := _dict.get('document_counts')) is not None: - args['document_counts'] = DocumentCounts.from_dict(document_counts) - if (disk_usage := _dict.get('disk_usage')) is not None: - args['disk_usage'] = CollectionDiskUsage.from_dict(disk_usage) - if (training_status := _dict.get('training_status')) is not None: - args['training_status'] = TrainingStatus.from_dict(training_status) - if (crawl_status := _dict.get('crawl_status')) is not None: - args['crawl_status'] = CollectionCrawlStatus.from_dict(crawl_status) - if (smart_document_understanding := - _dict.get('smart_document_understanding')) is not None: - args['smart_document_understanding'] = SduStatus.from_dict( - smart_document_understanding) - return cls(**args) - - @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 getattr( - self, 'collection_id') is not None: - _dict['collection_id'] = getattr(self, 'collection_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, - 'configuration_id') and self.configuration_id is not None: - _dict['configuration_id'] = self.configuration_id - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, - 'document_counts') and self.document_counts is not None: - if isinstance(self.document_counts, dict): - _dict['document_counts'] = self.document_counts - else: - _dict['document_counts'] = self.document_counts.to_dict() - if hasattr(self, 'disk_usage') and self.disk_usage is not None: - if isinstance(self.disk_usage, dict): - _dict['disk_usage'] = self.disk_usage - else: - _dict['disk_usage'] = self.disk_usage.to_dict() - if hasattr(self, - 'training_status') and self.training_status is not None: - if isinstance(self.training_status, dict): - _dict['training_status'] = self.training_status - else: - _dict['training_status'] = self.training_status.to_dict() - if hasattr(self, 'crawl_status') and self.crawl_status is not None: - if isinstance(self.crawl_status, dict): - _dict['crawl_status'] = self.crawl_status - else: - _dict['crawl_status'] = self.crawl_status.to_dict() - if hasattr(self, 'smart_document_understanding' - ) and self.smart_document_understanding is not None: - if isinstance(self.smart_document_understanding, dict): - _dict[ - 'smart_document_understanding'] = self.smart_document_understanding - else: - _dict[ - 'smart_document_understanding'] = self.smart_document_understanding.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 Collection object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Collection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the collection. - """ - - ACTIVE = 'active' - PENDING = 'pending' - MAINTENANCE = 'maintenance' - - -class CollectionCrawlStatus: - """ - Object containing information about the crawl status of this collection. - - :param SourceStatus source_crawl: (optional) Object containing source crawl - status information. - """ - - def __init__( - self, - *, - source_crawl: Optional['SourceStatus'] = None, - ) -> None: - """ - Initialize a CollectionCrawlStatus object. - - :param SourceStatus source_crawl: (optional) Object containing source crawl - status information. - """ - self.source_crawl = source_crawl - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionCrawlStatus': - """Initialize a CollectionCrawlStatus object from a json dictionary.""" - args = {} - if (source_crawl := _dict.get('source_crawl')) is not None: - args['source_crawl'] = SourceStatus.from_dict(source_crawl) - return cls(**args) - - @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: - if isinstance(self.source_crawl, dict): - _dict['source_crawl'] = self.source_crawl - else: - _dict['source_crawl'] = self.source_crawl.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 CollectionCrawlStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'CollectionCrawlStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CollectionDiskUsage: - """ - Summary of the disk usage statistics for this collection. - - :param int used_bytes: (optional) Number of bytes used by the collection. - """ - - def __init__( - self, - *, - used_bytes: Optional[int] = None, - ) -> None: - """ - Initialize a CollectionDiskUsage object. - - """ - self.used_bytes = used_bytes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionDiskUsage': - """Initialize a CollectionDiskUsage object from a json dictionary.""" - args = {} - if (used_bytes := _dict.get('used_bytes')) is not None: - args['used_bytes'] = used_bytes - return cls(**args) - - @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 getattr(self, - 'used_bytes') is not None: - _dict['used_bytes'] = getattr(self, 'used_bytes') - 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 CollectionDiskUsage object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'CollectionDiskUsage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CollectionUsage: - """ - Summary of the collection usage in the environment. - - :param int available: (optional) Number of active collections in the - environment. - :param int maximum_allowed: (optional) Total number of collections allowed in - the environment. - """ - - def __init__( - self, - *, - available: Optional[int] = None, - maximum_allowed: Optional[int] = None, - ) -> None: - """ - Initialize a CollectionUsage object. - - """ - self.available = available - self.maximum_allowed = maximum_allowed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionUsage': - """Initialize a CollectionUsage object from a json dictionary.""" - args = {} - if (available := _dict.get('available')) is not None: - args['available'] = available - if (maximum_allowed := _dict.get('maximum_allowed')) is not None: - args['maximum_allowed'] = maximum_allowed - return cls(**args) - - @classmethod - 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 getattr(self, - 'available') is not None: - _dict['available'] = getattr(self, 'available') - if hasattr(self, 'maximum_allowed') and getattr( - self, 'maximum_allowed') is not None: - _dict['maximum_allowed'] = getattr(self, 'maximum_allowed') - 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 CollectionUsage object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'CollectionUsage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Completions: - """ - An object containing an array of autocompletion suggestions. - - :param List[str] completions: (optional) Array of autcomplete suggestion based - on the provided prefix. - """ - - def __init__( - self, - *, - completions: Optional[List[str]] = None, - ) -> None: - """ - Initialize a Completions object. - - :param List[str] completions: (optional) Array of autcomplete suggestion - based on the provided prefix. - """ - self.completions = completions - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Completions': - """Initialize a Completions object from a json dictionary.""" - args = {} - if (completions := _dict.get('completions')) is not None: - args['completions'] = completions - return cls(**args) - - @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 _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: '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: 'Completions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Configuration: - """ - A custom configuration for the environment. - - :param str configuration_id: (optional) The unique identifier of the - configuration. - :param str name: The name of the configuration. - :param datetime created: (optional) The creation date of the configuration in - the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param datetime updated: (optional) The timestamp of when the configuration was - last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :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 enrichment - settings for the configuration. - :param List[NormalizationOperation] normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a normalized - form. Operations are executed in the order that they appear in the array. - :param Source source: (optional) Object containing source parameters for the - configuration. - """ - - def __init__( - self, - name: str, - *, - configuration_id: Optional[str] = None, - created: Optional[datetime] = None, - updated: Optional[datetime] = None, - description: Optional[str] = None, - conversions: Optional['Conversions'] = None, - enrichments: Optional[List['Enrichment']] = None, - normalizations: Optional[List['NormalizationOperation']] = None, - source: Optional['Source'] = None, - ) -> None: - """ - Initialize a Configuration object. - - :param str name: The name of the configuration. - :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 - enrichment settings for the configuration. - :param List[NormalizationOperation] normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a - normalized form. Operations are executed in the order that they appear in - the array. - :param Source source: (optional) Object containing source parameters for - the configuration. - """ - self.configuration_id = configuration_id - self.name = name - self.created = created - self.updated = updated - self.description = description - self.conversions = conversions - self.enrichments = enrichments - self.normalizations = normalizations - self.source = source - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Configuration': - """Initialize a Configuration object from a json dictionary.""" - args = {} - if (configuration_id := _dict.get('configuration_id')) is not None: - args['configuration_id'] = configuration_id - if (name := _dict.get('name')) is not None: - args['name'] = name - else: - raise ValueError( - 'Required property \'name\' not present in Configuration JSON') - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - if (updated := _dict.get('updated')) is not None: - args['updated'] = string_to_datetime(updated) - if (description := _dict.get('description')) is not None: - args['description'] = description - if (conversions := _dict.get('conversions')) is not None: - args['conversions'] = Conversions.from_dict(conversions) - if (enrichments := _dict.get('enrichments')) is not None: - args['enrichments'] = [Enrichment.from_dict(v) for v in enrichments] - if (normalizations := _dict.get('normalizations')) is not None: - args['normalizations'] = [ - NormalizationOperation.from_dict(v) for v in normalizations - ] - if (source := _dict.get('source')) is not None: - args['source'] = Source.from_dict(source) - return cls(**args) - - @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, 'configuration_id') and getattr( - self, 'configuration_id') is not None: - _dict['configuration_id'] = getattr(self, 'configuration_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'conversions') and self.conversions is not None: - if isinstance(self.conversions, dict): - _dict['conversions'] = self.conversions - else: - _dict['conversions'] = self.conversions.to_dict() - if hasattr(self, 'enrichments') and self.enrichments is not None: - enrichments_list = [] - for v in self.enrichments: - if isinstance(v, dict): - enrichments_list.append(v) - else: - enrichments_list.append(v.to_dict()) - _dict['enrichments'] = enrichments_list - if hasattr(self, 'normalizations') and self.normalizations is not None: - normalizations_list = [] - for v in self.normalizations: - if isinstance(v, dict): - normalizations_list.append(v) - else: - normalizations_list.append(v.to_dict()) - _dict['normalizations'] = normalizations_list - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.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 Configuration object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Configuration') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Conversions: - """ - Document conversion settings. - - :param PdfSettings pdf: (optional) A list of PDF conversion settings. - :param WordSettings word: (optional) A list of Word conversion settings. - :param HtmlSettings html: (optional) A list of HTML conversion settings. - :param SegmentSettings segment: (optional) A list of Document Segmentation - settings. - :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. - :param bool image_text_recognition: (optional) When `true`, automatic text - extraction from images (this includes images embedded in supported document - formats, for example PDF, and suppported image formats, for example TIFF) is - performed on documents uploaded to the collection. This field is supported on - **Advanced** and higher plans only. **Lite** plans do not support image text - recognition. - """ - - def __init__( - self, - *, - pdf: Optional['PdfSettings'] = None, - word: Optional['WordSettings'] = None, - html: Optional['HtmlSettings'] = None, - segment: Optional['SegmentSettings'] = None, - json_normalizations: Optional[List['NormalizationOperation']] = None, - image_text_recognition: Optional[bool] = None, - ) -> None: - """ - Initialize a Conversions object. - - :param PdfSettings pdf: (optional) A list of PDF conversion settings. - :param WordSettings word: (optional) A list of Word conversion settings. - :param HtmlSettings html: (optional) A list of HTML conversion settings. - :param SegmentSettings segment: (optional) A list of Document Segmentation - settings. - :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. - :param bool image_text_recognition: (optional) When `true`, automatic text - extraction from images (this includes images embedded in supported document - formats, for example PDF, and suppported image formats, for example TIFF) - is performed on documents uploaded to the collection. This field is - supported on **Advanced** and higher plans only. **Lite** plans do not - support image text recognition. - """ - self.pdf = pdf - self.word = word - self.html = html - self.segment = segment - self.json_normalizations = json_normalizations - self.image_text_recognition = image_text_recognition - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Conversions': - """Initialize a Conversions object from a json dictionary.""" - args = {} - if (pdf := _dict.get('pdf')) is not None: - args['pdf'] = PdfSettings.from_dict(pdf) - if (word := _dict.get('word')) is not None: - args['word'] = WordSettings.from_dict(word) - if (html := _dict.get('html')) is not None: - args['html'] = HtmlSettings.from_dict(html) - if (segment := _dict.get('segment')) is not None: - args['segment'] = SegmentSettings.from_dict(segment) - if (json_normalizations := - _dict.get('json_normalizations')) is not None: - args['json_normalizations'] = [ - NormalizationOperation.from_dict(v) for v in json_normalizations - ] - if (image_text_recognition := - _dict.get('image_text_recognition')) is not None: - args['image_text_recognition'] = image_text_recognition - return cls(**args) - - @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: - if isinstance(self.pdf, dict): - _dict['pdf'] = self.pdf - else: - _dict['pdf'] = self.pdf.to_dict() - if hasattr(self, 'word') and self.word is not None: - if isinstance(self.word, dict): - _dict['word'] = self.word - else: - _dict['word'] = self.word.to_dict() - if hasattr(self, 'html') and self.html is not None: - if isinstance(self.html, dict): - _dict['html'] = self.html - else: - _dict['html'] = self.html.to_dict() - if hasattr(self, 'segment') and self.segment is not None: - if isinstance(self.segment, dict): - _dict['segment'] = self.segment - else: - _dict['segment'] = self.segment.to_dict() - if hasattr( - self, - 'json_normalizations') and self.json_normalizations is not None: - json_normalizations_list = [] - for v in self.json_normalizations: - if isinstance(v, dict): - json_normalizations_list.append(v) - else: - json_normalizations_list.append(v.to_dict()) - _dict['json_normalizations'] = json_normalizations_list - if hasattr(self, 'image_text_recognition' - ) and self.image_text_recognition is not None: - _dict['image_text_recognition'] = self.image_text_recognition - 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 Conversions object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Conversions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CreateEventResponse: - """ - An object defining the event being created. - - :param str type: (optional) The event type that was created. - :param EventData data: (optional) Query event data object. - """ - - def __init__( - self, - *, - type: Optional[str] = None, - data: Optional['EventData'] = None, - ) -> None: - """ - Initialize a CreateEventResponse object. - - :param str type: (optional) The event type that was created. - :param EventData data: (optional) Query event data object. - """ - self.type = type - self.data = data - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CreateEventResponse': - """Initialize a CreateEventResponse object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (data := _dict.get('data')) is not None: - args['data'] = EventData.from_dict(data) - return cls(**args) - - @classmethod - 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: - _dict['type'] = self.type - if hasattr(self, 'data') and self.data is not None: - if isinstance(self.data, dict): - _dict['data'] = self.data - else: - _dict['data'] = self.data.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 CreateEventResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'CreateEventResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The event type that was created. - """ - - CLICK = 'click' - - -class CredentialDetails: - """ - Object containing details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - - :param str credential_type: (optional) The authentication method for this - credentials definition. The **credential_type** specified must be supported by - the **source_type**. The following combinations are possible: - - `"source_type": "box"` - valid `credential_type`s: `oauth2` - - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with - **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - - "source_type": "cloud_object_storage"` - valid `credential_type`s: - `aws4_hmac`. - :param str client_id: (optional) The **client_id** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. - :param str enterprise_id: (optional) The **enterprise_id** of the Box site that - these credentials connect to. Only valid, and required, with a **source_type** - of `box`. - :param str url: (optional) The **url** of the source that these credentials - connect to. Only valid, and required, with a **credential_type** of - `username_password`, `noauth`, and `basic`. - :param str username: (optional) The **username** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `saml`, `username_password`, `basic`, or `ntlm_v1`. - :param str organization_url: (optional) The **organization_url** of the source - that these credentials connect to. Only valid, and required, with a - **credential_type** of `saml`. - :param str site_collection_path: (optional) The **site_collection.path** of the - source that these credentials connect to. Only valid, and required, with a - **source_type** of `sharepoint`. - :param str client_secret: (optional) The **client_secret** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only used - when creating or modifying **credentials**. - :param str public_key_id: (optional) The **public_key_id** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only used - when creating or modifying **credentials**. - :param str private_key: (optional) The **private_key** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or - modifying **credentials**. - :param str passphrase: (optional) The **passphrase** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or - modifying **credentials**. - :param str password: (optional) The **password** of the source that these - credentials connect to. Only valid, and required, with **credential_type**s of - `saml`, `username_password`, `basic`, or `ntlm_v1`. - **Note:** When used with a **source_type** of `salesforce`, the password - consists of the Salesforce password and a valid Salesforce security token - concatenated. This value is never returned and is only used when creating or - modifying **credentials**. - :param str gateway_id: (optional) The ID of the **gateway** to be connected - through (when connecting to intranet sites). Only valid with a - **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are created - using the `/v1/environments/{environment_id}/gateways` methods. - :param str source_version: (optional) The type of Sharepoint repository to - connect to. Only valid, and required, with a **source_type** of `sharepoint`. - :param str web_application_url: (optional) SharePoint OnPrem WebApplication URL. - Only valid, and required, with a **source_version** of `2016`. If a port is not - supplied, the default to port `80` for http and port `443` for https connections - are used. - :param str domain: (optional) The domain used to log in to your OnPrem - SharePoint account. Only valid, and required, with a **source_version** of - `2016`. - :param str endpoint: (optional) The endpoint associated with the cloud object - store that your are connecting to. Only valid, and required, with a - **credential_type** of `aws4_hmac`. - :param str access_key_id: (optional) The access key ID associated with the cloud - object store. Only valid, and required, with a **credential_type** of - `aws4_hmac`. This value is never returned and is only used when creating or - modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - :param str secret_access_key: (optional) The secret access key associated with - the cloud object store. Only valid, and required, with a **credential_type** of - `aws4_hmac`. This value is never returned and is only used when creating or - modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - """ - - def __init__( - self, - *, - credential_type: Optional[str] = None, - client_id: Optional[str] = None, - enterprise_id: Optional[str] = None, - url: Optional[str] = None, - username: Optional[str] = None, - organization_url: Optional[str] = None, - site_collection_path: Optional[str] = None, - client_secret: Optional[str] = None, - public_key_id: Optional[str] = None, - private_key: Optional[str] = None, - passphrase: Optional[str] = None, - password: Optional[str] = None, - gateway_id: Optional[str] = None, - source_version: Optional[str] = None, - web_application_url: Optional[str] = None, - domain: Optional[str] = None, - endpoint: Optional[str] = None, - access_key_id: Optional[str] = None, - secret_access_key: Optional[str] = None, - ) -> None: - """ - Initialize a CredentialDetails object. - - :param str credential_type: (optional) The authentication method for this - credentials definition. The **credential_type** specified must be - supported by the **source_type**. The following combinations are possible: - - `"source_type": "box"` - valid `credential_type`s: `oauth2` - - `"source_type": "salesforce"` - valid `credential_type`s: - `username_password` - - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with - **source_version** of `online`, or `ntlm_v1` with **source_version** of - `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or - `basic` - - "source_type": "cloud_object_storage"` - valid `credential_type`s: - `aws4_hmac`. - :param str client_id: (optional) The **client_id** of the source that these - credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. - :param str enterprise_id: (optional) The **enterprise_id** of the Box site - that these credentials connect to. Only valid, and required, with a - **source_type** of `box`. - :param str url: (optional) The **url** of the source that these credentials - connect to. Only valid, and required, with a **credential_type** of - `username_password`, `noauth`, and `basic`. - :param str username: (optional) The **username** of the source that these - credentials connect to. Only valid, and required, with a - **credential_type** of `saml`, `username_password`, `basic`, or `ntlm_v1`. - :param str organization_url: (optional) The **organization_url** of the - source that these credentials connect to. Only valid, and required, with a - **credential_type** of `saml`. - :param str site_collection_path: (optional) The **site_collection.path** of - the source that these credentials connect to. Only valid, and required, - with a **source_type** of `sharepoint`. - :param str client_secret: (optional) The **client_secret** of the source - that these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str public_key_id: (optional) The **public_key_id** of the source - that these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str private_key: (optional) The **private_key** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str passphrase: (optional) The **passphrase** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str password: (optional) The **password** of the source that these - credentials connect to. Only valid, and required, with **credential_type**s - of `saml`, `username_password`, `basic`, or `ntlm_v1`. - **Note:** When used with a **source_type** of `salesforce`, the password - consists of the Salesforce password and a valid Salesforce security token - concatenated. This value is never returned and is only used when creating - or modifying **credentials**. - :param str gateway_id: (optional) The ID of the **gateway** to be connected - through (when connecting to intranet sites). Only valid with a - **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are - created using the `/v1/environments/{environment_id}/gateways` methods. - :param str source_version: (optional) The type of Sharepoint repository to - connect to. Only valid, and required, with a **source_type** of - `sharepoint`. - :param str web_application_url: (optional) SharePoint OnPrem WebApplication - URL. Only valid, and required, with a **source_version** of `2016`. If a - port is not supplied, the default to port `80` for http and port `443` for - https connections are used. - :param str domain: (optional) The domain used to log in to your OnPrem - SharePoint account. Only valid, and required, with a **source_version** of - `2016`. - :param str endpoint: (optional) The endpoint associated with the cloud - object store that your are connecting to. Only valid, and required, with a - **credential_type** of `aws4_hmac`. - :param str access_key_id: (optional) The access key ID associated with the - cloud object store. Only valid, and required, with a **credential_type** of - `aws4_hmac`. This value is never returned and is only used when creating or - modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - :param str secret_access_key: (optional) The secret access key associated - with the cloud object store. Only valid, and required, with a - **credential_type** of `aws4_hmac`. This value is never returned and is - only used when creating or modifying **credentials**. For more infomation, - see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - """ - self.credential_type = credential_type - self.client_id = client_id - self.enterprise_id = enterprise_id - self.url = url - self.username = username - self.organization_url = organization_url - self.site_collection_path = site_collection_path - self.client_secret = client_secret - self.public_key_id = public_key_id - self.private_key = private_key - self.passphrase = passphrase - self.password = password - self.gateway_id = gateway_id - self.source_version = source_version - self.web_application_url = web_application_url - self.domain = domain - self.endpoint = endpoint - self.access_key_id = access_key_id - self.secret_access_key = secret_access_key - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CredentialDetails': - """Initialize a CredentialDetails object from a json dictionary.""" - args = {} - if (credential_type := _dict.get('credential_type')) is not None: - args['credential_type'] = credential_type - if (client_id := _dict.get('client_id')) is not None: - args['client_id'] = client_id - if (enterprise_id := _dict.get('enterprise_id')) is not None: - args['enterprise_id'] = enterprise_id - if (url := _dict.get('url')) is not None: - args['url'] = url - if (username := _dict.get('username')) is not None: - args['username'] = username - if (organization_url := _dict.get('organization_url')) is not None: - args['organization_url'] = organization_url - if (site_collection_path := - _dict.get('site_collection.path')) is not None: - args['site_collection_path'] = site_collection_path - if (client_secret := _dict.get('client_secret')) is not None: - args['client_secret'] = client_secret - if (public_key_id := _dict.get('public_key_id')) is not None: - args['public_key_id'] = public_key_id - if (private_key := _dict.get('private_key')) is not None: - args['private_key'] = private_key - if (passphrase := _dict.get('passphrase')) is not None: - args['passphrase'] = passphrase - if (password := _dict.get('password')) is not None: - args['password'] = password - if (gateway_id := _dict.get('gateway_id')) is not None: - args['gateway_id'] = gateway_id - if (source_version := _dict.get('source_version')) is not None: - args['source_version'] = source_version - if (web_application_url := - _dict.get('web_application_url')) is not None: - args['web_application_url'] = web_application_url - if (domain := _dict.get('domain')) is not None: - args['domain'] = domain - if (endpoint := _dict.get('endpoint')) is not None: - args['endpoint'] = endpoint - if (access_key_id := _dict.get('access_key_id')) is not None: - args['access_key_id'] = access_key_id - if (secret_access_key := _dict.get('secret_access_key')) is not None: - args['secret_access_key'] = secret_access_key - return cls(**args) - - @classmethod - 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, - 'credential_type') and self.credential_type is not None: - _dict['credential_type'] = self.credential_type - if hasattr(self, 'client_id') and self.client_id is not None: - _dict['client_id'] = self.client_id - if hasattr(self, 'enterprise_id') and self.enterprise_id is not None: - _dict['enterprise_id'] = self.enterprise_id - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'username') and self.username is not None: - _dict['username'] = self.username - if hasattr(self, - 'organization_url') and self.organization_url is not None: - _dict['organization_url'] = self.organization_url - if hasattr(self, 'site_collection_path' - ) and self.site_collection_path is not None: - _dict['site_collection.path'] = self.site_collection_path - if hasattr(self, 'client_secret') and self.client_secret is not None: - _dict['client_secret'] = self.client_secret - if hasattr(self, 'public_key_id') and self.public_key_id is not None: - _dict['public_key_id'] = self.public_key_id - if hasattr(self, 'private_key') and self.private_key is not None: - _dict['private_key'] = self.private_key - if hasattr(self, 'passphrase') and self.passphrase is not None: - _dict['passphrase'] = self.passphrase - if hasattr(self, 'password') and self.password is not None: - _dict['password'] = self.password - if hasattr(self, 'gateway_id') and self.gateway_id is not None: - _dict['gateway_id'] = self.gateway_id - if hasattr(self, 'source_version') and self.source_version is not None: - _dict['source_version'] = self.source_version - if hasattr( - self, - 'web_application_url') and self.web_application_url is not None: - _dict['web_application_url'] = self.web_application_url - if hasattr(self, 'domain') and self.domain is not None: - _dict['domain'] = self.domain - if hasattr(self, 'endpoint') and self.endpoint is not None: - _dict['endpoint'] = self.endpoint - if hasattr(self, 'access_key_id') and self.access_key_id is not None: - _dict['access_key_id'] = self.access_key_id - if hasattr(self, - 'secret_access_key') and self.secret_access_key is not None: - _dict['secret_access_key'] = self.secret_access_key - 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 CredentialDetails object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'CredentialDetails') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class CredentialTypeEnum(str, Enum): - """ - The authentication method for this credentials definition. The - **credential_type** specified must be supported by the **source_type**. The - following combinations are possible: - - `"source_type": "box"` - valid `credential_type`s: `oauth2` - - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with - **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. - """ - - OAUTH2 = 'oauth2' - SAML = 'saml' - USERNAME_PASSWORD = 'username_password' - NOAUTH = 'noauth' - BASIC = 'basic' - NTLM_V1 = 'ntlm_v1' - AWS4_HMAC = 'aws4_hmac' - - class SourceVersionEnum(str, Enum): - """ - The type of Sharepoint repository to connect to. Only valid, and required, with a - **source_type** of `sharepoint`. - """ - - ONLINE = 'online' - - -class Credentials: - """ - Object containing credential information. - - :param str credential_id: (optional) Unique identifier for this set of - credentials. - :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of Enterprise - Box. - - `salesforce` indicates the credentials are used to connect to Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to an - IBM Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing - details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param StatusDetails status: (optional) Object that contains details about the - status of the authentication process. - """ - - def __init__( - self, - *, - credential_id: Optional[str] = None, - source_type: Optional[str] = None, - credential_details: Optional['CredentialDetails'] = None, - status: Optional['StatusDetails'] = None, - ) -> None: - """ - Initialize a Credentials object. - - :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of - Enterprise Box. - - `salesforce` indicates the credentials are used to connect to - Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to - an IBM Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing - details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param StatusDetails status: (optional) Object that contains details about - the status of the authentication process. - """ - self.credential_id = credential_id - self.source_type = source_type - self.credential_details = credential_details - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Credentials': - """Initialize a Credentials object from a json dictionary.""" - args = {} - if (credential_id := _dict.get('credential_id')) is not None: - args['credential_id'] = credential_id - if (source_type := _dict.get('source_type')) is not None: - args['source_type'] = source_type - if (credential_details := _dict.get('credential_details')) is not None: - args['credential_details'] = CredentialDetails.from_dict( - credential_details) - if (status := _dict.get('status')) is not None: - args['status'] = StatusDetails.from_dict(status) - return cls(**args) - - @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 getattr( - self, 'credential_id') is not None: - _dict['credential_id'] = getattr(self, 'credential_id') - if hasattr(self, 'source_type') and self.source_type is not None: - _dict['source_type'] = self.source_type - if hasattr( - self, - 'credential_details') and self.credential_details is not None: - if isinstance(self.credential_details, dict): - _dict['credential_details'] = self.credential_details - else: - _dict['credential_details'] = self.credential_details.to_dict() - if hasattr(self, 'status') and self.status is not None: - if isinstance(self.status, dict): - _dict['status'] = self.status - else: - _dict['status'] = self.status.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 Credentials object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Credentials') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class SourceTypeEnum(str, Enum): - """ - The source that this credentials object connects to. - - `box` indicates the credentials are used to connect an instance of Enterprise - Box. - - `salesforce` indicates the credentials are used to connect to Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to an IBM - Cloud Object Store. - """ - - BOX = 'box' - SALESFORCE = 'salesforce' - SHAREPOINT = 'sharepoint' - WEB_CRAWL = 'web_crawl' - CLOUD_OBJECT_STORAGE = 'cloud_object_storage' - - -class CredentialsList: - """ - Object containing array of credential definitions. - - :param List[Credentials] credentials: (optional) An array of credential - definitions that were created for this instance. - """ - - def __init__( - self, - *, - credentials: Optional[List['Credentials']] = None, - ) -> None: - """ - Initialize a CredentialsList object. - - :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: Dict) -> 'CredentialsList': - """Initialize a CredentialsList object from a json dictionary.""" - args = {} - if (credentials := _dict.get('credentials')) is not None: - args['credentials'] = [ - Credentials.from_dict(v) for v in credentials - ] - return cls(**args) - - @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: - credentials_list = [] - for v in self.credentials: - if isinstance(v, dict): - credentials_list.append(v) - else: - credentials_list.append(v.to_dict()) - _dict['credentials'] = credentials_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this CredentialsList object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'CredentialsList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DeleteCollectionResponse: - """ - Response object returned when deleting a colleciton. - - :param str collection_id: The unique identifier of the collection that is being - deleted. - :param str status: The status of the collection. The status of a successful - deletion operation is `deleted`. - """ - - def __init__( - self, - collection_id: str, - status: str, - ) -> None: - """ - Initialize a DeleteCollectionResponse object. - - :param str collection_id: The unique identifier of the collection that is - being deleted. - :param str status: The status of the collection. The status of a successful - deletion operation is `deleted`. - """ - self.collection_id = collection_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteCollectionResponse': - """Initialize a DeleteCollectionResponse object from a json dictionary.""" - args = {} - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - else: - raise ValueError( - 'Required property \'collection_id\' not present in DeleteCollectionResponse JSON' - ) - if (status := _dict.get('status')) is not None: - args['status'] = status - else: - raise ValueError( - 'Required property \'status\' not present in DeleteCollectionResponse JSON' - ) - return cls(**args) - - @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: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 DeleteCollectionResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'DeleteCollectionResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the collection. The status of a successful deletion operation is - `deleted`. - """ - - DELETED = 'deleted' - - -class DeleteConfigurationResponse: - """ - Information returned when a configuration is deleted. - - :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 any. - """ - - def __init__( - self, - configuration_id: str, - status: str, - *, - notices: Optional[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 - any. - """ - self.configuration_id = configuration_id - self.status = status - self.notices = notices - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteConfigurationResponse': - """Initialize a DeleteConfigurationResponse object from a json dictionary.""" - args = {} - if (configuration_id := _dict.get('configuration_id')) is not None: - args['configuration_id'] = configuration_id - else: - raise ValueError( - 'Required property \'configuration_id\' not present in DeleteConfigurationResponse JSON' - ) - if (status := _dict.get('status')) is not None: - args['status'] = status - else: - raise ValueError( - 'Required property \'status\' not present in DeleteConfigurationResponse JSON' - ) - if (notices := _dict.get('notices')) is not None: - args['notices'] = [Notice.from_dict(v) for v in notices] - return cls(**args) - - @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, - 'configuration_id') and self.configuration_id is not None: - _dict['configuration_id'] = self.configuration_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'notices') and self.notices is not None: - notices_list = [] - for v in self.notices: - if isinstance(v, dict): - notices_list.append(v) - else: - notices_list.append(v.to_dict()) - _dict['notices'] = notices_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DeleteConfigurationResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'DeleteConfigurationResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the configuration. A deleted configuration has the status deleted. - """ - - DELETED = 'deleted' - - -class DeleteCredentials: - """ - Object returned after credentials are deleted. - - :param str credential_id: (optional) The unique identifier of the credentials - that have been deleted. - :param str status: (optional) The status of the deletion request. - """ - - def __init__( - self, - *, - credential_id: Optional[str] = None, - status: Optional[str] = None, - ) -> None: - """ - Initialize a DeleteCredentials object. - - :param str credential_id: (optional) The unique identifier of the - credentials that have been deleted. - :param str status: (optional) The status of the deletion request. - """ - self.credential_id = credential_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteCredentials': - """Initialize a DeleteCredentials object from a json dictionary.""" - args = {} - if (credential_id := _dict.get('credential_id')) is not None: - args['credential_id'] = credential_id - if (status := _dict.get('status')) is not None: - args['status'] = status - return cls(**args) - - @classmethod - 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: - _dict['credential_id'] = self.credential_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 DeleteCredentials object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'DeleteCredentials') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the deletion request. - """ - - DELETED = 'deleted' - - -class DeleteDocumentResponse: - """ - Information returned when a document is deleted. - - :param str document_id: (optional) The unique identifier of the document. - :param str status: (optional) Status of the document. A deleted document has the - status deleted. - """ - - def __init__( - self, - *, - document_id: Optional[str] = None, - status: Optional[str] = None, - ) -> None: - """ - Initialize a DeleteDocumentResponse object. - - :param str document_id: (optional) The unique identifier of the document. - :param str status: (optional) Status of the document. A deleted document - has the status deleted. - """ - self.document_id = document_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': - """Initialize a DeleteDocumentResponse object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (status := _dict.get('status')) is not None: - args['status'] = status - return cls(**args) - - @classmethod - 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: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 DeleteDocumentResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'DeleteDocumentResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the document. A deleted document has the status deleted. - """ - - DELETED = 'deleted' - - -class DeleteEnvironmentResponse: - """ - Response object returned when deleting an environment. - - :param str environment_id: The unique identifier for the environment. - :param str status: Status of the environment. - """ - - def __init__( - self, - environment_id: str, - status: str, - ) -> None: - """ - Initialize a DeleteEnvironmentResponse object. - - :param str environment_id: The unique identifier for the environment. - :param str status: Status of the environment. - """ - self.environment_id = environment_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteEnvironmentResponse': - """Initialize a DeleteEnvironmentResponse object from a json dictionary.""" - args = {} - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - else: - raise ValueError( - 'Required property \'environment_id\' not present in DeleteEnvironmentResponse JSON' - ) - if (status := _dict.get('status')) is not None: - args['status'] = status - else: - raise ValueError( - 'Required property \'status\' not present in DeleteEnvironmentResponse JSON' - ) - return cls(**args) - - @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: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 DeleteEnvironmentResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'DeleteEnvironmentResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the environment. - """ - - DELETED = 'deleted' - - -class DiskUsage: - """ - Summary of the disk usage statistics for the environment. - - :param int used_bytes: (optional) Number of bytes within the environment's disk - capacity that are currently used to store data. - :param int maximum_allowed_bytes: (optional) Total number of bytes available in - the environment's disk capacity. - """ - - def __init__( - self, - *, - used_bytes: Optional[int] = None, - maximum_allowed_bytes: Optional[int] = None, - ) -> None: - """ - Initialize a DiskUsage object. - - """ - self.used_bytes = used_bytes - self.maximum_allowed_bytes = maximum_allowed_bytes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DiskUsage': - """Initialize a DiskUsage object from a json dictionary.""" - args = {} - if (used_bytes := _dict.get('used_bytes')) is not None: - args['used_bytes'] = used_bytes - if (maximum_allowed_bytes := - _dict.get('maximum_allowed_bytes')) is not None: - args['maximum_allowed_bytes'] = maximum_allowed_bytes - return cls(**args) - - @classmethod - 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 getattr(self, - 'used_bytes') is not None: - _dict['used_bytes'] = getattr(self, 'used_bytes') - if hasattr(self, 'maximum_allowed_bytes') and getattr( - self, 'maximum_allowed_bytes') is not None: - _dict['maximum_allowed_bytes'] = getattr(self, - 'maximum_allowed_bytes') - 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 DiskUsage object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'DiskUsage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentAccepted: - """ - Information returned after an uploaded document is accepted. - - :param str document_id: (optional) The unique identifier of the ingested - document. - :param str status: (optional) Status of the document in the ingestion process. A - status of `processing` is returned for documents that are ingested with a - *version* date before `2019-01-01`. The `pending` status is returned for all - others. - :param List[Notice] notices: (optional) Array of notices produced by the - document-ingestion process. - """ - - def __init__( - self, - *, - document_id: Optional[str] = None, - status: Optional[str] = None, - notices: Optional[List['Notice']] = None, - ) -> None: - """ - Initialize a DocumentAccepted object. - - :param str document_id: (optional) The unique identifier of the ingested - document. - :param str status: (optional) Status of the document in the ingestion - process. A status of `processing` is returned for documents that are - ingested with a *version* date before `2019-01-01`. The `pending` status is - returned for all others. - :param List[Notice] notices: (optional) Array of notices produced by the - document-ingestion process. - """ - self.document_id = document_id - self.status = status - self.notices = notices - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': - """Initialize a DocumentAccepted object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (notices := _dict.get('notices')) is not None: - args['notices'] = [Notice.from_dict(v) for v in notices] - return cls(**args) - - @classmethod - 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: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'notices') and self.notices is not None: - notices_list = [] - for v in self.notices: - if isinstance(v, dict): - notices_list.append(v) - else: - notices_list.append(v.to_dict()) - _dict['notices'] = notices_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DocumentAccepted object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'DocumentAccepted') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the document in the ingestion process. A status of `processing` is - returned for documents that are ingested with a *version* date before - `2019-01-01`. The `pending` status is returned for all others. - """ - - PROCESSING = 'processing' - PENDING = 'pending' - - -class DocumentCounts: - """ - Object containing collection document count information. - - :param int available: (optional) The total number of available documents in the - collection. - :param int processing: (optional) The number of documents in the collection that - are currently being processed. - :param int failed: (optional) The number of documents in the collection that - failed to be ingested. - :param int pending: (optional) The number of documents that have been uploaded - to the collection, but have not yet started processing. - """ - - def __init__( - self, - *, - available: Optional[int] = None, - processing: Optional[int] = None, - failed: Optional[int] = None, - pending: Optional[int] = None, - ) -> None: - """ - Initialize a DocumentCounts object. - - """ - self.available = available - self.processing = processing - self.failed = failed - self.pending = pending - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentCounts': - """Initialize a DocumentCounts object from a json dictionary.""" - args = {} - if (available := _dict.get('available')) is not None: - args['available'] = available - if (processing := _dict.get('processing')) is not None: - args['processing'] = processing - if (failed := _dict.get('failed')) is not None: - args['failed'] = failed - if (pending := _dict.get('pending')) is not None: - args['pending'] = pending - return cls(**args) - - @classmethod - 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 getattr(self, - 'available') is not None: - _dict['available'] = getattr(self, 'available') - if hasattr(self, 'processing') and getattr(self, - 'processing') is not None: - _dict['processing'] = getattr(self, 'processing') - if hasattr(self, 'failed') and getattr(self, 'failed') is not None: - _dict['failed'] = getattr(self, 'failed') - if hasattr(self, 'pending') and getattr(self, 'pending') is not None: - _dict['pending'] = getattr(self, 'pending') - 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 DocumentCounts object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'DocumentCounts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentStatus: - """ - Status information about a submitted document. - - :param str document_id: (optional) The unique identifier of the document. - :param str configuration_id: (optional) The unique identifier for the - configuration. - :param str status: (optional) Status of the document in the ingestion process. - :param str status_description: (optional) Description of the document status. - :param str filename: (optional) Name of the original source file (if available). - :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file - (formatted as a hexadecimal string). - :param List[Notice] notices: (optional) Array of notices produced by the - document-ingestion process. - """ - - def __init__( - self, - *, - document_id: Optional[str] = None, - configuration_id: Optional[str] = None, - status: Optional[str] = None, - status_description: Optional[str] = None, - filename: Optional[str] = None, - file_type: Optional[str] = None, - sha1: Optional[str] = None, - notices: Optional[List['Notice']] = None, - ) -> None: - """ - Initialize a DocumentStatus object. - - :param str filename: (optional) Name of the original source file (if - available). - :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file - (formatted as a hexadecimal string). - """ - self.document_id = document_id - self.configuration_id = configuration_id - self.status = status - self.status_description = status_description - self.filename = filename - self.file_type = file_type - self.sha1 = sha1 - self.notices = notices - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentStatus': - """Initialize a DocumentStatus object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (configuration_id := _dict.get('configuration_id')) is not None: - args['configuration_id'] = configuration_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (filename := _dict.get('filename')) is not None: - args['filename'] = filename - if (file_type := _dict.get('file_type')) is not None: - args['file_type'] = file_type - if (sha1 := _dict.get('sha1')) is not None: - args['sha1'] = sha1 - if (notices := _dict.get('notices')) is not None: - args['notices'] = [Notice.from_dict(v) for v in notices] - return cls(**args) - - @classmethod - 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 getattr(self, - 'document_id') is not None: - _dict['document_id'] = getattr(self, 'document_id') - if hasattr(self, 'configuration_id') and getattr( - self, 'configuration_id') is not None: - _dict['configuration_id'] = getattr(self, 'configuration_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, 'file_type') and self.file_type is not None: - _dict['file_type'] = self.file_type - if hasattr(self, 'sha1') and self.sha1 is not None: - _dict['sha1'] = self.sha1 - if hasattr(self, 'notices') and getattr(self, 'notices') is not None: - notices_list = [] - for v in getattr(self, 'notices'): - if isinstance(v, dict): - notices_list.append(v) - else: - notices_list.append(v.to_dict()) - _dict['notices'] = notices_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DocumentStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'DocumentStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the document in the ingestion process. - """ - - AVAILABLE = 'available' - AVAILABLE_WITH_NOTICES = 'available with notices' - FAILED = 'failed' - PROCESSING = 'processing' - PENDING = 'pending' - - class FileTypeEnum(str, Enum): - """ - The type of the original source file. - """ - - PDF = 'pdf' - HTML = 'html' - WORD = 'word' - JSON = 'json' - - -class Enrichment: - """ - Enrichment step to perform on the document. Each enrichment is performed on the - specified field in the order that they are listed in the configuration. - - :param str description: (optional) Describes what the enrichment step does. - :param str destination_field: Field where enrichments will be stored. This field - must already exist or be at most 1 level deeper than an existing field. For - example, if `text` is a top-level field with no sub-fields, `text.foo` is a - valid destination but `text.foo.bar` is not. - :param str source_field: Field to be enriched. - Arrays can be specified as the **source_field** if the **enrichment** service - for this enrichment is set to `natural_language_undstanding`. - :param bool overwrite: (optional) Indicates that the enrichments will overwrite - the destination_field field if it already exists. - :param str enrichment: Name of the enrichment service to call. The only - supported option is `natural_language_understanding`. The `elements` option is - deprecated and support ended on 10 July 2020. - The **options** object must contain Natural Language Understanding options. - :param bool ignore_downstream_errors: (optional) If true, then most errors - generated during the enrichment process will be treated as warnings and will not - cause the document to fail processing. - :param EnrichmentOptions options: (optional) Options that are specific to a - particular enrichment. - The `elements` enrichment type is deprecated. Use the [Create a - project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of - the Discovery v2 API to create a `content_intelligence` project type instead. - """ - - def __init__( - self, - destination_field: str, - source_field: str, - enrichment: str, - *, - description: Optional[str] = None, - overwrite: Optional[bool] = None, - ignore_downstream_errors: Optional[bool] = None, - options: Optional['EnrichmentOptions'] = None, - ) -> None: - """ - Initialize a Enrichment object. - - :param str destination_field: Field where enrichments will be stored. This - field must already exist or be at most 1 level deeper than an existing - field. For example, if `text` is a top-level field with no sub-fields, - `text.foo` is a valid destination but `text.foo.bar` is not. - :param str source_field: Field to be enriched. - Arrays can be specified as the **source_field** if the **enrichment** - service for this enrichment is set to `natural_language_undstanding`. - :param str enrichment: Name of the enrichment service to call. The only - supported option is `natural_language_understanding`. The `elements` option - is deprecated and support ended on 10 July 2020. - The **options** object must contain Natural Language Understanding - options. - :param str description: (optional) Describes what the enrichment step does. - :param bool overwrite: (optional) Indicates that the enrichments will - overwrite the destination_field field if it already exists. - :param bool ignore_downstream_errors: (optional) If true, then most errors - generated during the enrichment process will be treated as warnings and - will not cause the document to fail processing. - :param EnrichmentOptions options: (optional) Options that are specific to a - particular enrichment. - The `elements` enrichment type is deprecated. Use the [Create a - project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method - of the Discovery v2 API to create a `content_intelligence` project type - instead. - """ - self.description = description - self.destination_field = destination_field - self.source_field = source_field - self.overwrite = overwrite - self.enrichment = enrichment - self.ignore_downstream_errors = ignore_downstream_errors - self.options = options - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Enrichment': - """Initialize a Enrichment object from a json dictionary.""" - args = {} - if (description := _dict.get('description')) is not None: - args['description'] = description - if (destination_field := _dict.get('destination_field')) is not None: - args['destination_field'] = destination_field - else: - raise ValueError( - 'Required property \'destination_field\' not present in Enrichment JSON' - ) - if (source_field := _dict.get('source_field')) is not None: - args['source_field'] = source_field - else: - raise ValueError( - 'Required property \'source_field\' not present in Enrichment JSON' - ) - if (overwrite := _dict.get('overwrite')) is not None: - args['overwrite'] = overwrite - if (enrichment := _dict.get('enrichment')) is not None: - args['enrichment'] = enrichment - else: - raise ValueError( - 'Required property \'enrichment\' not present in Enrichment JSON' - ) - if (ignore_downstream_errors := - _dict.get('ignore_downstream_errors')) is not None: - args['ignore_downstream_errors'] = ignore_downstream_errors - if (options := _dict.get('options')) is not None: - args['options'] = EnrichmentOptions.from_dict(options) - return cls(**args) - - @classmethod - 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: - _dict['description'] = self.description - if hasattr(self, - 'destination_field') and self.destination_field is not None: - _dict['destination_field'] = self.destination_field - if hasattr(self, 'source_field') and self.source_field is not None: - _dict['source_field'] = self.source_field - if hasattr(self, 'overwrite') and self.overwrite is not None: - _dict['overwrite'] = self.overwrite - if hasattr(self, 'enrichment') and self.enrichment is not None: - _dict['enrichment'] = self.enrichment - if hasattr(self, 'ignore_downstream_errors' - ) and self.ignore_downstream_errors is not None: - _dict['ignore_downstream_errors'] = self.ignore_downstream_errors - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options - else: - _dict['options'] = self.options.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Enrichment object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Enrichment') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class EnrichmentOptions: - """ - Options that are specific to a particular enrichment. - The `elements` enrichment type is deprecated. Use the [Create a - project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of the - Discovery v2 API to create a `content_intelligence` project type instead. - - :param NluEnrichmentFeatures features: (optional) Object containing Natural - Language Understanding features to be used. - :param str language: (optional) ISO 639-1 code indicating the language to use - for the analysis. This code overrides the automatic language detection performed - by the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), - `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` - (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, - automatic detection is recommended. - :param str model: (optional) Deprecated: The element extraction model to use, - which can be `contract` only. The `elements` enrichment is deprecated. - """ - - def __init__( - self, - *, - features: Optional['NluEnrichmentFeatures'] = None, - language: Optional[str] = None, - model: Optional[str] = None, - ) -> None: - """ - Initialize a EnrichmentOptions object. - - :param NluEnrichmentFeatures features: (optional) Object containing Natural - Language Understanding features to be used. - :param str language: (optional) ISO 639-1 code indicating the language to - use for the analysis. This code overrides the automatic language detection - performed by the service. Valid codes are `ar` (Arabic), `en` (English), - `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` - (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features - support all languages, automatic detection is recommended. - :param str model: (optional) Deprecated: The element extraction model to - use, which can be `contract` only. The `elements` enrichment is deprecated. - """ - self.features = features - self.language = language - self.model = model - - @classmethod - def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': - """Initialize a EnrichmentOptions object from a json dictionary.""" - args = {} - if (features := _dict.get('features')) is not None: - args['features'] = NluEnrichmentFeatures.from_dict(features) - if (language := _dict.get('language')) is not None: - args['language'] = language - if (model := _dict.get('model')) is not None: - args['model'] = model - return cls(**args) - - @classmethod - 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: - if isinstance(self.features, dict): - _dict['features'] = self.features - else: - _dict['features'] = self.features.to_dict() - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'model') and self.model is not None: - _dict['model'] = self.model - 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 EnrichmentOptions object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'EnrichmentOptions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class LanguageEnum(str, Enum): - """ - ISO 639-1 code indicating the language to use for the analysis. This code - overrides the automatic language detection performed by the service. Valid codes - are `ar` (Arabic), `en` (English), `fr` (French), `de` (German), `it` (Italian), - `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** - Not all features support all languages, automatic detection is recommended. - """ - - AR = 'ar' - EN = 'en' - FR = 'fr' - DE = 'de' - IT = 'it' - PT = 'pt' - RU = 'ru' - ES = 'es' - SV = 'sv' - - -class Environment: - """ - Details about an environment. - - :param str environment_id: (optional) Unique identifier for the environment. - :param str name: (optional) Name that identifies the environment. - :param str description: (optional) Description of the environment. - :param datetime created: (optional) Creation date of the environment, in the - format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :param datetime updated: (optional) Date of most recent environment update, in - the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :param str status: (optional) Current status of the environment. `resizing` is - displayed when a request to increase the environment size has been made, but is - still in the process of being completed. - :param bool read_only: (optional) If `true`, the environment contains read-only - collections that are maintained by IBM. - :param str size: (optional) Current size of the environment. - :param str requested_size: (optional) The new size requested for this - environment. Only returned when the environment *status* is `resizing`. - *Note:* Querying and indexing can still be performed during an environment - upsize. - :param IndexCapacity index_capacity: (optional) Details about the resource usage - and capacity of the environment. - :param SearchStatus search_status: (optional) Information about the Continuous - Relevancy Training for this environment. - """ - - def __init__( - self, - *, - environment_id: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - created: Optional[datetime] = None, - updated: Optional[datetime] = None, - status: Optional[str] = None, - read_only: Optional[bool] = None, - size: Optional[str] = None, - requested_size: Optional[str] = None, - index_capacity: Optional['IndexCapacity'] = None, - search_status: Optional['SearchStatus'] = None, - ) -> None: - """ - Initialize a Environment object. - - :param str name: (optional) Name that identifies the environment. - :param str description: (optional) Description of the environment. - :param str size: (optional) Current size of the environment. - :param str requested_size: (optional) The new size requested for this - environment. Only returned when the environment *status* is `resizing`. - *Note:* Querying and indexing can still be performed during an environment - upsize. - :param IndexCapacity index_capacity: (optional) Details about the resource - usage and capacity of the environment. - :param SearchStatus search_status: (optional) Information about the - Continuous Relevancy Training for this environment. - """ - self.environment_id = environment_id - self.name = name - self.description = description - self.created = created - self.updated = updated - self.status = status - self.read_only = read_only - self.size = size - self.requested_size = requested_size - self.index_capacity = index_capacity - self.search_status = search_status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Environment': - """Initialize a Environment object from a json dictionary.""" - args = {} - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - if (updated := _dict.get('updated')) is not None: - args['updated'] = string_to_datetime(updated) - if (status := _dict.get('status')) is not None: - args['status'] = status - if (read_only := _dict.get('read_only')) is not None: - args['read_only'] = read_only - if (size := _dict.get('size')) is not None: - args['size'] = size - if (requested_size := _dict.get('requested_size')) is not None: - args['requested_size'] = requested_size - if (index_capacity := _dict.get('index_capacity')) is not None: - args['index_capacity'] = IndexCapacity.from_dict(index_capacity) - if (search_status := _dict.get('search_status')) is not None: - args['search_status'] = SearchStatus.from_dict(search_status) - return cls(**args) - - @classmethod - 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 getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'read_only') and getattr(self, - 'read_only') is not None: - _dict['read_only'] = getattr(self, 'read_only') - if hasattr(self, 'size') and self.size is not None: - _dict['size'] = self.size - if hasattr(self, 'requested_size') and self.requested_size is not None: - _dict['requested_size'] = self.requested_size - if hasattr(self, 'index_capacity') and self.index_capacity is not None: - if isinstance(self.index_capacity, dict): - _dict['index_capacity'] = self.index_capacity - else: - _dict['index_capacity'] = self.index_capacity.to_dict() - if hasattr(self, 'search_status') and self.search_status is not None: - if isinstance(self.search_status, dict): - _dict['search_status'] = self.search_status - else: - _dict['search_status'] = self.search_status.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 Environment object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Environment') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Current status of the environment. `resizing` is displayed when a request to - increase the environment size has been made, but is still in the process of being - completed. - """ - - ACTIVE = 'active' - PENDING = 'pending' - MAINTENANCE = 'maintenance' - RESIZING = 'resizing' - - class SizeEnum(str, Enum): - """ - Current size of the environment. - """ - - LT = 'LT' - XS = 'XS' - S = 'S' - MS = 'MS' - M = 'M' - ML = 'ML' - L = 'L' - XL = 'XL' - XXL = 'XXL' - XXXL = 'XXXL' - - -class EnvironmentDocuments: - """ - Summary of the document usage statistics for the environment. - - :param int available: (optional) Number of documents indexed for the - environment. - :param int maximum_allowed: (optional) Total number of documents allowed in the - environment's capacity. - """ - - def __init__( - self, - *, - available: Optional[int] = None, - maximum_allowed: Optional[int] = None, - ) -> None: - """ - Initialize a EnvironmentDocuments object. - - """ - self.available = available - self.maximum_allowed = maximum_allowed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'EnvironmentDocuments': - """Initialize a EnvironmentDocuments object from a json dictionary.""" - args = {} - if (available := _dict.get('available')) is not None: - args['available'] = available - if (maximum_allowed := _dict.get('maximum_allowed')) is not None: - args['maximum_allowed'] = maximum_allowed - return cls(**args) - - @classmethod - 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, 'available') and getattr(self, - 'available') is not None: - _dict['available'] = getattr(self, 'available') - if hasattr(self, 'maximum_allowed') and getattr( - self, 'maximum_allowed') is not None: - _dict['maximum_allowed'] = getattr(self, 'maximum_allowed') - 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 EnvironmentDocuments object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'EnvironmentDocuments') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class EventData: - """ - Query event data object. - - :param str environment_id: The **environment_id** associated with the query that - the event is associated with. - :param str session_token: The session token that was returned as part of the - query results that this event is associated with. - :param datetime client_timestamp: (optional) The optional timestamp for the - event that was created. If not provided, the time that the event was created in - the log was used. - :param int display_rank: (optional) The rank of the result item which the event - is associated with. - :param str collection_id: The **collection_id** of the document that this event - is associated with. - :param str document_id: The **document_id** of the document that this event is - associated with. - :param str query_id: (optional) The query identifier stored in the log. The - query and any events associated with that query are stored with the same - **query_id**. - """ - - def __init__( - self, - environment_id: str, - session_token: str, - collection_id: str, - document_id: str, - *, - client_timestamp: Optional[datetime] = None, - display_rank: Optional[int] = None, - query_id: Optional[str] = None, - ) -> None: - """ - Initialize a EventData object. - - :param str environment_id: The **environment_id** associated with the query - that the event is associated with. - :param str session_token: The session token that was returned as part of - the query results that this event is associated with. - :param str collection_id: The **collection_id** of the document that this - event is associated with. - :param str document_id: The **document_id** of the document that this event - is associated with. - :param datetime client_timestamp: (optional) The optional timestamp for the - event that was created. If not provided, the time that the event was - created in the log was used. - :param int display_rank: (optional) The rank of the result item which the - event is associated with. - """ - self.environment_id = environment_id - self.session_token = session_token - self.client_timestamp = client_timestamp - self.display_rank = display_rank - self.collection_id = collection_id - self.document_id = document_id - self.query_id = query_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'EventData': - """Initialize a EventData object from a json dictionary.""" - args = {} - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - else: - raise ValueError( - 'Required property \'environment_id\' not present in EventData JSON' - ) - if (session_token := _dict.get('session_token')) is not None: - args['session_token'] = session_token - else: - raise ValueError( - 'Required property \'session_token\' not present in EventData JSON' - ) - if (client_timestamp := _dict.get('client_timestamp')) is not None: - args['client_timestamp'] = string_to_datetime(client_timestamp) - if (display_rank := _dict.get('display_rank')) is not None: - args['display_rank'] = display_rank - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - else: - raise ValueError( - 'Required property \'collection_id\' not present in EventData JSON' - ) - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - else: - raise ValueError( - 'Required property \'document_id\' not present in EventData JSON' - ) - if (query_id := _dict.get('query_id')) is not None: - args['query_id'] = query_id - return cls(**args) - - @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: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'session_token') and self.session_token is not None: - _dict['session_token'] = self.session_token - if hasattr(self, - 'client_timestamp') and self.client_timestamp is not None: - _dict['client_timestamp'] = datetime_to_string( - self.client_timestamp) - if hasattr(self, 'display_rank') and self.display_rank is not None: - _dict['display_rank'] = self.display_rank - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'query_id') and getattr(self, 'query_id') is not None: - _dict['query_id'] = getattr(self, 'query_id') - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this EventData object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'EventData') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Expansion: - """ - An expansion definition. Each object respresents one set of expandable strings. For - example, you could have expansions for the word `hot` in one object, and expansions - for the word `cold` in another. - - :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. - :param List[str] expanded_terms: A list of terms that this expansion will be - expanded to. If specified without **input_terms**, it also functions as the - input term list. - """ - - def __init__( - self, - expanded_terms: List[str], - *, - input_terms: Optional[List[str]] = None, - ) -> None: - """ - Initialize a Expansion object. - - :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 - expanded for this expansion. If specified, only the items in this list are - expanded. - """ - self.input_terms = input_terms - self.expanded_terms = expanded_terms - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Expansion': - """Initialize a Expansion object from a json dictionary.""" - args = {} - if (input_terms := _dict.get('input_terms')) is not None: - args['input_terms'] = input_terms - if (expanded_terms := _dict.get('expanded_terms')) is not None: - args['expanded_terms'] = expanded_terms - else: - raise ValueError( - 'Required property \'expanded_terms\' not present in Expansion JSON' - ) - return cls(**args) - - @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: - _dict['input_terms'] = self.input_terms - if hasattr(self, 'expanded_terms') and self.expanded_terms is not None: - _dict['expanded_terms'] = self.expanded_terms - 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 Expansion object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Expansion') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Expansions: - """ - The query expansion definitions for the specified collection. - - :param List[Expansion] expansions: An array of query expansion definitions. - Each object in the **expansions** array represents a term or set of terms that - will be expanded into other terms. Each expansion object can be configured as - bidirectional or unidirectional. Bidirectional means that all terms are expanded - to all other terms in the object. Unidirectional means that a set list of terms - can be expanded into a second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. When - found in a query, all items in the **expanded_terms** array are then expanded to - the other items in the same array. - To create a uni-directional expansion, specify both an array of **input_terms** - and an array of **expanded_terms**. When items in the **input_terms** array are - present in a query, they are expanded using the items listed in the - **expanded_terms** array. - """ - - def __init__( - self, - expansions: List['Expansion'], - ) -> None: - """ - Initialize a Expansions object. - - :param List[Expansion] expansions: An array of query expansion definitions. - Each object in the **expansions** array represents a term or set of terms - that will be expanded into other terms. Each expansion object can be - configured as bidirectional or unidirectional. Bidirectional means that all - terms are expanded to all other terms in the object. Unidirectional means - that a set list of terms can be expanded into a second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. - When found in a query, all items in the **expanded_terms** array are then - expanded to the other items in the same array. - To create a uni-directional expansion, specify both an array of - **input_terms** and an array of **expanded_terms**. When items in the - **input_terms** array are present in a query, they are expanded using the - items listed in the **expanded_terms** array. - """ - self.expansions = expansions - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Expansions': - """Initialize a Expansions object from a json dictionary.""" - args = {} - if (expansions := _dict.get('expansions')) is not None: - args['expansions'] = [Expansion.from_dict(v) for v in expansions] - else: - raise ValueError( - 'Required property \'expansions\' not present in Expansions JSON' - ) - return cls(**args) - - @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: - expansions_list = [] - for v in self.expansions: - if isinstance(v, dict): - expansions_list.append(v) - else: - expansions_list.append(v.to_dict()) - _dict['expansions'] = expansions_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Expansions object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Expansions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Field: - """ - Object containing field details. - - :param str field: (optional) The name of the field. - :param str type: (optional) The type of the field. - """ - - def __init__( - self, - *, - field: Optional[str] = None, - type: Optional[str] = None, - ) -> None: - """ - Initialize a Field object. - - """ - self.field = field - self.type = type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Field': - """Initialize a Field object from a json dictionary.""" - args = {} - if (field := _dict.get('field')) is not None: - args['field'] = field - if (type := _dict.get('type')) is not None: - args['type'] = type - return cls(**args) - - @classmethod - 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 getattr(self, 'field') is not None: - _dict['field'] = getattr(self, 'field') - if hasattr(self, 'type') and getattr(self, 'type') is not None: - _dict['type'] = getattr(self, 'type') - 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 Field object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Field') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The type of the field. - """ - - NESTED = 'nested' - STRING = 'string' - DATE = 'date' - LONG = 'long' - INTEGER = 'integer' - SHORT = 'short' - BYTE = 'byte' - DOUBLE = 'double' - FLOAT = 'float' - BOOLEAN = 'boolean' - BINARY = 'binary' - - -class FontSetting: - """ - Font matching configuration. - - :param int level: (optional) The HTML heading level that any content with the - matching font is converted to. - :param int min_size: (optional) The minimum size of the font to match. - :param int max_size: (optional) The maximum size of the font to match. - :param bool bold: (optional) When `true`, the font is matched if it is bold. - :param bool italic: (optional) When `true`, the font is matched if it is italic. - :param str name: (optional) The name of the font. - """ - - def __init__( - self, - *, - level: Optional[int] = None, - min_size: Optional[int] = None, - max_size: Optional[int] = None, - bold: Optional[bool] = None, - italic: Optional[bool] = None, - name: Optional[str] = None, - ) -> None: - """ - Initialize a FontSetting object. - - :param int level: (optional) The HTML heading level that any content with - the matching font is converted to. - :param int min_size: (optional) The minimum size of the font to match. - :param int max_size: (optional) The maximum size of the font to match. - :param bool bold: (optional) When `true`, the font is matched if it is - bold. - :param bool italic: (optional) When `true`, the font is matched if it is - italic. - :param str name: (optional) The name of the font. - """ - self.level = level - self.min_size = min_size - self.max_size = max_size - self.bold = bold - self.italic = italic - self.name = name - - @classmethod - def from_dict(cls, _dict: Dict) -> 'FontSetting': - """Initialize a FontSetting object from a json dictionary.""" - args = {} - if (level := _dict.get('level')) is not None: - args['level'] = level - if (min_size := _dict.get('min_size')) is not None: - args['min_size'] = min_size - if (max_size := _dict.get('max_size')) is not None: - args['max_size'] = max_size - if (bold := _dict.get('bold')) is not None: - args['bold'] = bold - if (italic := _dict.get('italic')) is not None: - args['italic'] = italic - if (name := _dict.get('name')) is not None: - args['name'] = name - return cls(**args) - - @classmethod - 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: - _dict['level'] = self.level - if hasattr(self, 'min_size') and self.min_size is not None: - _dict['min_size'] = self.min_size - if hasattr(self, 'max_size') and self.max_size is not None: - _dict['max_size'] = self.max_size - if hasattr(self, 'bold') and self.bold is not None: - _dict['bold'] = self.bold - if hasattr(self, 'italic') and self.italic is not None: - _dict['italic'] = self.italic - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - 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 FontSetting object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'FontSetting') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Gateway: - """ - Object describing a specific gateway. - - :param str gateway_id: (optional) The gateway ID of the gateway. - :param str name: (optional) The user defined name of the gateway. - :param str status: (optional) The current status of the gateway. `connected` - means the gateway is connected to the remotly installed gateway. `idle` means - this gateway is not currently in use. - :param str token: (optional) The generated **token** for this gateway. The value - of this field is used when configuring the remotly installed gateway. - :param str token_id: (optional) The generated **token_id** for this gateway. The - value of this field is used when configuring the remotly installed gateway. - """ - - def __init__( - self, - *, - gateway_id: Optional[str] = None, - name: Optional[str] = None, - status: Optional[str] = None, - token: Optional[str] = None, - token_id: Optional[str] = None, - ) -> None: - """ - Initialize a Gateway object. - - :param str gateway_id: (optional) The gateway ID of the gateway. - :param str name: (optional) The user defined name of the gateway. - :param str status: (optional) The current status of the gateway. - `connected` means the gateway is connected to the remotly installed - gateway. `idle` means this gateway is not currently in use. - :param str token: (optional) The generated **token** for this gateway. The - value of this field is used when configuring the remotly installed gateway. - :param str token_id: (optional) The generated **token_id** for this - gateway. The value of this field is used when configuring the remotly - installed gateway. - """ - self.gateway_id = gateway_id - self.name = name - self.status = status - self.token = token - self.token_id = token_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Gateway': - """Initialize a Gateway object from a json dictionary.""" - args = {} - if (gateway_id := _dict.get('gateway_id')) is not None: - args['gateway_id'] = gateway_id - if (name := _dict.get('name')) is not None: - args['name'] = name - if (status := _dict.get('status')) is not None: - args['status'] = status - if (token := _dict.get('token')) is not None: - args['token'] = token - if (token_id := _dict.get('token_id')) is not None: - args['token_id'] = token_id - return cls(**args) - - @classmethod - 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: - _dict['gateway_id'] = self.gateway_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'token') and self.token is not None: - _dict['token'] = self.token - if hasattr(self, 'token_id') and self.token_id is not None: - _dict['token_id'] = self.token_id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Gateway object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Gateway') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The current status of the gateway. `connected` means the gateway is connected to - the remotly installed gateway. `idle` means this gateway is not currently in use. - """ - - CONNECTED = 'connected' - IDLE = 'idle' - - -class GatewayDelete: - """ - Gatway deletion confirmation. - - :param str gateway_id: (optional) The gateway ID of the deleted gateway. - :param str status: (optional) The status of the request. - """ - - def __init__( - self, - *, - gateway_id: Optional[str] = None, - status: Optional[str] = None, - ) -> None: - """ - Initialize a GatewayDelete object. - - :param str gateway_id: (optional) The gateway ID of the deleted gateway. - :param str status: (optional) The status of the request. - """ - self.gateway_id = gateway_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'GatewayDelete': - """Initialize a GatewayDelete object from a json dictionary.""" - args = {} - if (gateway_id := _dict.get('gateway_id')) is not None: - args['gateway_id'] = gateway_id - if (status := _dict.get('status')) is not None: - args['status'] = status - return cls(**args) - - @classmethod - 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: - _dict['gateway_id'] = self.gateway_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 GatewayDelete object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'GatewayDelete') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class GatewayList: - """ - Object containing gateways array. - - :param List[Gateway] gateways: (optional) Array of configured gateway - connections. - """ - - def __init__( - self, - *, - gateways: Optional[List['Gateway']] = None, - ) -> None: - """ - Initialize a GatewayList object. - - :param List[Gateway] gateways: (optional) Array of configured gateway - connections. - """ - self.gateways = gateways - - @classmethod - def from_dict(cls, _dict: Dict) -> 'GatewayList': - """Initialize a GatewayList object from a json dictionary.""" - args = {} - if (gateways := _dict.get('gateways')) is not None: - args['gateways'] = [Gateway.from_dict(v) for v in gateways] - return cls(**args) - - @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: - gateways_list = [] - for v in self.gateways: - if isinstance(v, dict): - gateways_list.append(v) - else: - gateways_list.append(v.to_dict()) - _dict['gateways'] = gateways_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this GatewayList object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'GatewayList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class HtmlSettings: - """ - A list of HTML conversion settings. - - :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 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 attributes - to keep in the converted document. - :param List[str] exclude_tag_attributes: (optional) Array of HTML tag attributes - to exclude. - """ - - def __init__( - self, - *, - exclude_tags_completely: Optional[List[str]] = None, - exclude_tags_keep_content: Optional[List[str]] = None, - keep_content: Optional['XPathPatterns'] = None, - exclude_content: Optional['XPathPatterns'] = None, - keep_tag_attributes: Optional[List[str]] = None, - exclude_tag_attributes: Optional[List[str]] = None, - ) -> None: - """ - Initialize a HtmlSettings object. - - :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 - 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 - attributes to keep in the converted document. - :param List[str] exclude_tag_attributes: (optional) Array of HTML tag - attributes to exclude. - """ - self.exclude_tags_completely = exclude_tags_completely - self.exclude_tags_keep_content = exclude_tags_keep_content - self.keep_content = keep_content - self.exclude_content = exclude_content - self.keep_tag_attributes = keep_tag_attributes - self.exclude_tag_attributes = exclude_tag_attributes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'HtmlSettings': - """Initialize a HtmlSettings object from a json dictionary.""" - args = {} - if (exclude_tags_completely := - _dict.get('exclude_tags_completely')) is not None: - args['exclude_tags_completely'] = exclude_tags_completely - if (exclude_tags_keep_content := - _dict.get('exclude_tags_keep_content')) is not None: - args['exclude_tags_keep_content'] = exclude_tags_keep_content - if (keep_content := _dict.get('keep_content')) is not None: - args['keep_content'] = XPathPatterns.from_dict(keep_content) - if (exclude_content := _dict.get('exclude_content')) is not None: - args['exclude_content'] = XPathPatterns.from_dict(exclude_content) - if (keep_tag_attributes := - _dict.get('keep_tag_attributes')) is not None: - args['keep_tag_attributes'] = keep_tag_attributes - if (exclude_tag_attributes := - _dict.get('exclude_tag_attributes')) is not None: - args['exclude_tag_attributes'] = exclude_tag_attributes - return cls(**args) - - @classmethod - 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' - ) and self.exclude_tags_completely is not None: - _dict['exclude_tags_completely'] = self.exclude_tags_completely - if hasattr(self, 'exclude_tags_keep_content' - ) and self.exclude_tags_keep_content is not None: - _dict['exclude_tags_keep_content'] = self.exclude_tags_keep_content - if hasattr(self, 'keep_content') and self.keep_content is not None: - if isinstance(self.keep_content, dict): - _dict['keep_content'] = self.keep_content - else: - _dict['keep_content'] = self.keep_content.to_dict() - if hasattr(self, - 'exclude_content') and self.exclude_content is not None: - if isinstance(self.exclude_content, dict): - _dict['exclude_content'] = self.exclude_content - else: - _dict['exclude_content'] = self.exclude_content.to_dict() - if hasattr( - self, - 'keep_tag_attributes') and self.keep_tag_attributes is not None: - _dict['keep_tag_attributes'] = self.keep_tag_attributes - if hasattr(self, 'exclude_tag_attributes' - ) and self.exclude_tag_attributes is not None: - _dict['exclude_tag_attributes'] = self.exclude_tag_attributes - 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 HtmlSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'HtmlSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IndexCapacity: - """ - Details about the resource usage and capacity of the environment. - - :param EnvironmentDocuments documents: (optional) Summary of the document usage - statistics for the environment. - :param DiskUsage disk_usage: (optional) Summary of the disk usage statistics for - the environment. - :param CollectionUsage collections: (optional) Summary of the collection usage - in the environment. - """ - - def __init__( - self, - *, - documents: Optional['EnvironmentDocuments'] = None, - disk_usage: Optional['DiskUsage'] = None, - collections: Optional['CollectionUsage'] = None, - ) -> None: - """ - Initialize a IndexCapacity object. - - :param EnvironmentDocuments documents: (optional) Summary of the document - usage statistics for the environment. - :param DiskUsage disk_usage: (optional) Summary of the disk usage - statistics for the environment. - :param CollectionUsage collections: (optional) Summary of the collection - usage in the environment. - """ - self.documents = documents - self.disk_usage = disk_usage - self.collections = collections - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IndexCapacity': - """Initialize a IndexCapacity object from a json dictionary.""" - args = {} - if (documents := _dict.get('documents')) is not None: - args['documents'] = EnvironmentDocuments.from_dict(documents) - if (disk_usage := _dict.get('disk_usage')) is not None: - args['disk_usage'] = DiskUsage.from_dict(disk_usage) - if (collections := _dict.get('collections')) is not None: - args['collections'] = CollectionUsage.from_dict(collections) - return cls(**args) - - @classmethod - 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: - if isinstance(self.documents, dict): - _dict['documents'] = self.documents - else: - _dict['documents'] = self.documents.to_dict() - if hasattr(self, 'disk_usage') and self.disk_usage is not None: - if isinstance(self.disk_usage, dict): - _dict['disk_usage'] = self.disk_usage - else: - _dict['disk_usage'] = self.disk_usage.to_dict() - if hasattr(self, 'collections') and self.collections is not None: - if isinstance(self.collections, dict): - _dict['collections'] = self.collections - else: - _dict['collections'] = self.collections.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 IndexCapacity object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'IndexCapacity') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListCollectionFieldsResponse: - """ - The list of fetched fields. - The fields are returned using a fully qualified name format, however, the format - differs slightly from that used by the query operations. - * Fields which contain nested JSON objects are assigned a type of "nested". - * Fields which belong to a nested object are prefixed with `.properties` (for - example, `warnings.properties.severity` means that the `warnings` object has a - property called `severity`). - * Fields returned from the News collection are prefixed with - `v{N}-fullnews-t3-{YEAR}.mappings` (for example, - `v5-fullnews-t3-2016.mappings.text.properties.author`). - - :param List[Field] fields: (optional) An array containing information about each - field in the collections. - """ - - def __init__( - self, - *, - fields: Optional[List['Field']] = None, - ) -> None: - """ - Initialize a ListCollectionFieldsResponse object. - - :param List[Field] fields: (optional) An array containing information about - each field in the collections. - """ - self.fields = fields - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListCollectionFieldsResponse': - """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" - args = {} - if (fields := _dict.get('fields')) is not None: - args['fields'] = [Field.from_dict(v) for v in fields] - return cls(**args) - - @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: - fields_list = [] - for v in self.fields: - if isinstance(v, dict): - fields_list.append(v) - else: - fields_list.append(v.to_dict()) - _dict['fields'] = fields_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this ListCollectionFieldsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'ListCollectionFieldsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListCollectionsResponse: - """ - Response object containing an array of collection details. - - :param List[Collection] collections: (optional) An array containing information - about each collection in the environment. - """ - - def __init__( - self, - *, - collections: Optional[List['Collection']] = None, - ) -> None: - """ - Initialize a ListCollectionsResponse object. - - :param List[Collection] collections: (optional) An array containing - information about each collection in the environment. - """ - self.collections = collections - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': - """Initialize a ListCollectionsResponse object from a json dictionary.""" - args = {} - if (collections := _dict.get('collections')) is not None: - args['collections'] = [Collection.from_dict(v) for v in collections] - return cls(**args) - - @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: - collections_list = [] - for v in self.collections: - if isinstance(v, dict): - collections_list.append(v) - else: - collections_list.append(v.to_dict()) - _dict['collections'] = collections_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this ListCollectionsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'ListCollectionsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListConfigurationsResponse: - """ - Object containing an array of available configurations. - - :param List[Configuration] configurations: (optional) An array of configurations - that are available for the service instance. - """ - - def __init__( - self, - *, - configurations: Optional[List['Configuration']] = None, - ) -> None: - """ - Initialize a ListConfigurationsResponse object. - - :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: Dict) -> 'ListConfigurationsResponse': - """Initialize a ListConfigurationsResponse object from a json dictionary.""" - args = {} - if (configurations := _dict.get('configurations')) is not None: - args['configurations'] = [ - Configuration.from_dict(v) for v in configurations - ] - return cls(**args) - - @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: - configurations_list = [] - for v in self.configurations: - if isinstance(v, dict): - configurations_list.append(v) - else: - configurations_list.append(v.to_dict()) - _dict['configurations'] = configurations_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this ListConfigurationsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'ListConfigurationsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListEnvironmentsResponse: - """ - Response object containing an array of configured environments. - - :param List[Environment] environments: (optional) An array of [environments] - that are available for the service instance. - """ - - def __init__( - self, - *, - environments: Optional[List['Environment']] = None, - ) -> None: - """ - Initialize a ListEnvironmentsResponse object. - - :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: Dict) -> 'ListEnvironmentsResponse': - """Initialize a ListEnvironmentsResponse object from a json dictionary.""" - args = {} - if (environments := _dict.get('environments')) is not None: - args['environments'] = [ - Environment.from_dict(v) for v in environments - ] - return cls(**args) - - @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: - environments_list = [] - for v in self.environments: - if isinstance(v, dict): - environments_list.append(v) - else: - environments_list.append(v.to_dict()) - _dict['environments'] = environments_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this ListEnvironmentsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'ListEnvironmentsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LogQueryResponse: - """ - Object containing results that match the requested **logs** query. - - :param int matching_results: (optional) Number of matching results. - :param List[LogQueryResponseResult] results: (optional) Array of log query - response results. - """ - - def __init__( - self, - *, - matching_results: Optional[int] = None, - results: Optional[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 - response results. - """ - self.matching_results = matching_results - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponse': - """Initialize a LogQueryResponse object from a json dictionary.""" - args = {} - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - if (results := _dict.get('results')) is not None: - args['results'] = [ - LogQueryResponseResult.from_dict(v) for v in results - ] - return cls(**args) - - @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, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this LogQueryResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'LogQueryResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LogQueryResponseResult: - """ - Individual result object for a **logs** query. Each object represents either a query - to a Discovery collection or an event that is associated with a query. - - :param str environment_id: (optional) The environment ID that is associated with - this log entry. - :param str customer_id: (optional) The **customer_id** label that was specified - in the header of the query or event API call that corresponds to this log entry. - :param str document_type: (optional) The type of log entry returned. - **query** indicates that the log represents the results of a call to the single - collection **query** method. - **event** indicates that the log represents a call to the **events** API. - :param str natural_language_query: (optional) The value of the - **natural_language_query** query parameter that was used to create these - results. Only returned with logs of type **query**. - **Note:** Other query parameters (such as **filter** or **deduplicate**) might - have been used with this query, but are not recorded. - :param LogQueryResponseResultDocuments document_results: (optional) Object - containing result information that was returned by the query used to create this - log entry. Only returned with logs of type `query`. - :param datetime created_timestamp: (optional) Date that the log result was - created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime client_timestamp: (optional) Date specified by the user when - recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only returned - with logs of type **event**. - :param str query_id: (optional) Identifier that corresponds to the - **natural_language_query** string used in the original or associated query. All - **event** and **query** log entries that have the same original - **natural_language_query** string also have them same **query_id**. This field - can be used to recall all **event** and **query** log results that have the same - original query (**event** logs do not contain the original - **natural_language_query** field). - :param str session_token: (optional) Unique identifier (within a 24-hour period) - that identifies a single `query` log and any `event` logs that were created for - it. - **Note:** If the exact same query is run at the exact same time on different - days, the **session_token** for those queries might be identical. However, the - **created_timestamp** differs. - **Note:** Session tokens are case sensitive. To avoid matching on session tokens - that are identical except for case, use the exact match operator (`::`) when you - query for a specific session token. - :param str collection_id: (optional) The collection ID of the document - associated with this event. Only returned with logs of type `event`. - :param int display_rank: (optional) The original display rank of the document - associated with this event. Only returned with logs of type `event`. - :param str document_id: (optional) The document ID of the document associated - with this event. Only returned with logs of type `event`. - :param str event_type: (optional) The type of event that this object - respresents. Possible values are - - `query` the log of a query to a collection - - `click` the result of a call to the **events** endpoint. - :param str result_type: (optional) The type of result that this **event** is - associated with. Only returned with logs of type `event`. - """ - - def __init__( - self, - *, - environment_id: Optional[str] = None, - customer_id: Optional[str] = None, - document_type: Optional[str] = None, - natural_language_query: Optional[str] = None, - document_results: Optional['LogQueryResponseResultDocuments'] = None, - created_timestamp: Optional[datetime] = None, - client_timestamp: Optional[datetime] = None, - query_id: Optional[str] = None, - session_token: Optional[str] = None, - collection_id: Optional[str] = None, - display_rank: Optional[int] = None, - document_id: Optional[str] = None, - event_type: Optional[str] = None, - result_type: Optional[str] = None, - ) -> None: - """ - Initialize a LogQueryResponseResult object. - - :param str environment_id: (optional) The environment ID that is associated - with this log entry. - :param str customer_id: (optional) The **customer_id** label that was - specified in the header of the query or event API call that corresponds to - this log entry. - :param str document_type: (optional) The type of log entry returned. - **query** indicates that the log represents the results of a call to the - single collection **query** method. - **event** indicates that the log represents a call to the **events** API. - :param str natural_language_query: (optional) The value of the - **natural_language_query** query parameter that was used to create these - results. Only returned with logs of type **query**. - **Note:** Other query parameters (such as **filter** or **deduplicate**) - might have been used with this query, but are not recorded. - :param LogQueryResponseResultDocuments document_results: (optional) Object - containing result information that was returned by the query used to create - this log entry. Only returned with logs of type `query`. - :param datetime created_timestamp: (optional) Date that the log result was - created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime client_timestamp: (optional) Date specified by the user - when recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only - returned with logs of type **event**. - :param str query_id: (optional) Identifier that corresponds to the - **natural_language_query** string used in the original or associated query. - All **event** and **query** log entries that have the same original - **natural_language_query** string also have them same **query_id**. This - field can be used to recall all **event** and **query** log results that - have the same original query (**event** logs do not contain the original - **natural_language_query** field). - :param str session_token: (optional) Unique identifier (within a 24-hour - period) that identifies a single `query` log and any `event` logs that were - created for it. - **Note:** If the exact same query is run at the exact same time on - different days, the **session_token** for those queries might be identical. - However, the **created_timestamp** differs. - **Note:** Session tokens are case sensitive. To avoid matching on session - tokens that are identical except for case, use the exact match operator - (`::`) when you query for a specific session token. - :param str collection_id: (optional) The collection ID of the document - associated with this event. Only returned with logs of type `event`. - :param int display_rank: (optional) The original display rank of the - document associated with this event. Only returned with logs of type - `event`. - :param str document_id: (optional) The document ID of the document - associated with this event. Only returned with logs of type `event`. - :param str event_type: (optional) The type of event that this object - respresents. Possible values are - - `query` the log of a query to a collection - - `click` the result of a call to the **events** endpoint. - :param str result_type: (optional) The type of result that this **event** - is associated with. Only returned with logs of type `event`. - """ - self.environment_id = environment_id - self.customer_id = customer_id - self.document_type = document_type - self.natural_language_query = natural_language_query - self.document_results = document_results - self.created_timestamp = created_timestamp - self.client_timestamp = client_timestamp - self.query_id = query_id - self.session_token = session_token - self.collection_id = collection_id - self.display_rank = display_rank - self.document_id = document_id - self.event_type = event_type - self.result_type = result_type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResult': - """Initialize a LogQueryResponseResult object from a json dictionary.""" - args = {} - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (customer_id := _dict.get('customer_id')) is not None: - args['customer_id'] = customer_id - if (document_type := _dict.get('document_type')) is not None: - args['document_type'] = document_type - if (natural_language_query := - _dict.get('natural_language_query')) is not None: - args['natural_language_query'] = natural_language_query - if (document_results := _dict.get('document_results')) is not None: - args[ - 'document_results'] = LogQueryResponseResultDocuments.from_dict( - document_results) - if (created_timestamp := _dict.get('created_timestamp')) is not None: - args['created_timestamp'] = string_to_datetime(created_timestamp) - if (client_timestamp := _dict.get('client_timestamp')) is not None: - args['client_timestamp'] = string_to_datetime(client_timestamp) - if (query_id := _dict.get('query_id')) is not None: - args['query_id'] = query_id - if (session_token := _dict.get('session_token')) is not None: - args['session_token'] = session_token - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - if (display_rank := _dict.get('display_rank')) is not None: - args['display_rank'] = display_rank - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (event_type := _dict.get('event_type')) is not None: - args['event_type'] = event_type - if (result_type := _dict.get('result_type')) is not None: - args['result_type'] = result_type - return cls(**args) - - @classmethod - 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: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'customer_id') and self.customer_id is not None: - _dict['customer_id'] = self.customer_id - if hasattr(self, 'document_type') and self.document_type is not None: - _dict['document_type'] = self.document_type - if hasattr(self, 'natural_language_query' - ) and self.natural_language_query is not None: - _dict['natural_language_query'] = self.natural_language_query - if hasattr(self, - 'document_results') and self.document_results is not None: - if isinstance(self.document_results, dict): - _dict['document_results'] = self.document_results - else: - _dict['document_results'] = self.document_results.to_dict() - if hasattr(self, - 'created_timestamp') and self.created_timestamp is not None: - _dict['created_timestamp'] = datetime_to_string( - self.created_timestamp) - if hasattr(self, - 'client_timestamp') and self.client_timestamp is not None: - _dict['client_timestamp'] = datetime_to_string( - self.client_timestamp) - if hasattr(self, 'query_id') and self.query_id is not None: - _dict['query_id'] = self.query_id - if hasattr(self, 'session_token') and self.session_token is not None: - _dict['session_token'] = self.session_token - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'display_rank') and self.display_rank is not None: - _dict['display_rank'] = self.display_rank - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'event_type') and self.event_type is not None: - _dict['event_type'] = self.event_type - if hasattr(self, 'result_type') and self.result_type is not None: - _dict['result_type'] = self.result_type - 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 LogQueryResponseResult object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'LogQueryResponseResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class DocumentTypeEnum(str, Enum): - """ - The type of log entry returned. - **query** indicates that the log represents the results of a call to the single - collection **query** method. - **event** indicates that the log represents a call to the **events** API. - """ - - QUERY = 'query' - EVENT = 'event' - - class EventTypeEnum(str, Enum): - """ - The type of event that this object respresents. Possible values are - - `query` the log of a query to a collection - - `click` the result of a call to the **events** endpoint. - """ - - CLICK = 'click' - QUERY = 'query' - - class ResultTypeEnum(str, Enum): - """ - The type of result that this **event** is associated with. Only returned with logs - of type `event`. - """ - - DOCUMENT = 'document' - - -class LogQueryResponseResultDocuments: - """ - Object containing result information that was returned by the query used to create - this log entry. Only returned with logs of type `query`. - - :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. - """ - - def __init__( - self, - *, - results: Optional[List['LogQueryResponseResultDocumentsResult']] = None, - count: Optional[int] = None, - ) -> None: - """ - Initialize a LogQueryResponseResultDocuments object. - - :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. - """ - self.results = results - self.count = count - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocuments': - """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" - args = {} - if (results := _dict.get('results')) is not None: - args['results'] = [ - LogQueryResponseResultDocumentsResult.from_dict(v) - for v in results - ] - if (count := _dict.get('count')) is not None: - args['count'] = count - return cls(**args) - - @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: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - 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 LogQueryResponseResultDocuments object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'LogQueryResponseResultDocuments') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LogQueryResponseResultDocumentsResult: - """ - Each object in the **results** array corresponds to an individual document returned by - the original query. - - :param int position: (optional) The result rank of this document. A position of - `1` indicates that it was the first returned result. - :param str document_id: (optional) The **document_id** of the document that this - result represents. - :param float score: (optional) The raw score of this result. A higher score - indicates a greater match to the query parameters. - :param float confidence: (optional) The confidence score of the result's - analysis. A higher score indicating greater confidence. - :param str collection_id: (optional) The **collection_id** of the document - represented by this result. - """ - - def __init__( - self, - *, - position: Optional[int] = None, - document_id: Optional[str] = None, - score: Optional[float] = None, - confidence: Optional[float] = None, - collection_id: Optional[str] = None, - ) -> None: - """ - Initialize a LogQueryResponseResultDocumentsResult object. - - :param int position: (optional) The result rank of this document. A - position of `1` indicates that it was the first returned result. - :param str document_id: (optional) The **document_id** of the document that - this result represents. - :param float score: (optional) The raw score of this result. A higher score - indicates a greater match to the query parameters. - :param float confidence: (optional) The confidence score of the result's - analysis. A higher score indicating greater confidence. - :param str collection_id: (optional) The **collection_id** of the document - represented by this result. - """ - self.position = position - self.document_id = document_id - self.score = score - self.confidence = confidence - self.collection_id = collection_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocumentsResult': - """Initialize a LogQueryResponseResultDocumentsResult object from a json dictionary.""" - args = {} - if (position := _dict.get('position')) is not None: - args['position'] = position - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (score := _dict.get('score')) is not None: - args['score'] = score - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - return cls(**args) - - @classmethod - 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: - _dict['position'] = self.position - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this LogQueryResponseResultDocumentsResult object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'LogQueryResponseResultDocumentsResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricAggregation: - """ - An aggregation analyzing log information for queries and events. - - :param str interval: (optional) The measurement interval for this metric. 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 - aggregation query results. - """ - - def __init__( - self, - *, - interval: Optional[str] = None, - event_type: Optional[str] = None, - results: Optional[List['MetricAggregationResult']] = None, - ) -> None: - """ - Initialize a MetricAggregation object. - - :param str interval: (optional) The measurement interval for this metric. - 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 - aggregation query results. - """ - self.interval = interval - self.event_type = event_type - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricAggregation': - """Initialize a MetricAggregation object from a json dictionary.""" - args = {} - if (interval := _dict.get('interval')) is not None: - args['interval'] = interval - if (event_type := _dict.get('event_type')) is not None: - args['event_type'] = event_type - if (results := _dict.get('results')) is not None: - args['results'] = [ - MetricAggregationResult.from_dict(v) for v in results - ] - return cls(**args) - - @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: - _dict['interval'] = self.interval - if hasattr(self, 'event_type') and self.event_type is not None: - _dict['event_type'] = self.event_type - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MetricAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'MetricAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricAggregationResult: - """ - Aggregation result data for the requested metric. - - :param datetime key_as_string: (optional) Date in string form representing the - start of this interval. - :param int key: (optional) Unix epoch time equivalent of the **key_as_string**, - that represents the start of this interval. - :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated events - divided by the total number of queries for the interval. Only returned with - **event_rate** metrics. - """ - - def __init__( - self, - *, - key_as_string: Optional[datetime] = None, - key: Optional[int] = None, - matching_results: Optional[int] = None, - event_rate: Optional[float] = None, - ) -> None: - """ - Initialize a MetricAggregationResult object. - - :param datetime key_as_string: (optional) Date in string form representing - the start of this interval. - :param int key: (optional) Unix epoch time equivalent of the - **key_as_string**, that represents the start of this interval. - :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated - events divided by the total number of queries for the interval. Only - returned with **event_rate** metrics. - """ - self.key_as_string = key_as_string - self.key = key - self.matching_results = matching_results - self.event_rate = event_rate - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricAggregationResult': - """Initialize a MetricAggregationResult object from a json dictionary.""" - args = {} - if (key_as_string := _dict.get('key_as_string')) is not None: - args['key_as_string'] = string_to_datetime(key_as_string) - if (key := _dict.get('key')) is not None: - args['key'] = key - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - if (event_rate := _dict.get('event_rate')) is not None: - args['event_rate'] = event_rate - return cls(**args) - - @classmethod - 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: - _dict['key_as_string'] = datetime_to_string(self.key_as_string) - 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, 'event_rate') and self.event_rate is not None: - _dict['event_rate'] = self.event_rate - 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 MetricAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'MetricAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricResponse: - """ - The response generated from a call to a **metrics** method. - - :param List[MetricAggregation] aggregations: (optional) Array of metric - aggregations. - """ - - def __init__( - self, - *, - aggregations: Optional[List['MetricAggregation']] = None, - ) -> None: - """ - Initialize a MetricResponse object. - - :param List[MetricAggregation] aggregations: (optional) Array of metric - aggregations. - """ - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricResponse': - """Initialize a MetricResponse object from a json dictionary.""" - args = {} - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - MetricAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @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: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MetricResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'MetricResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricTokenAggregation: - """ - An aggregation analyzing log information for queries and events. - - :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 results - for the metric token aggregation. - """ - - def __init__( - self, - *, - event_type: Optional[str] = None, - results: Optional[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 - results for the metric token aggregation. - """ - self.event_type = event_type - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregation': - """Initialize a MetricTokenAggregation object from a json dictionary.""" - args = {} - if (event_type := _dict.get('event_type')) is not None: - args['event_type'] = event_type - if (results := _dict.get('results')) is not None: - args['results'] = [ - MetricTokenAggregationResult.from_dict(v) for v in results - ] - return cls(**args) - - @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: - _dict['event_type'] = self.event_type - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MetricTokenAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'MetricTokenAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricTokenAggregationResult: - """ - Aggregation result data for the requested metric. - - :param str key: (optional) The content of the **natural_language_query** - parameter used in the query that this result represents. - :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated events - divided by the total number of queries currently stored (queries and events are - stored in the log for 30 days). - """ - - def __init__( - self, - *, - key: Optional[str] = None, - matching_results: Optional[int] = None, - event_rate: Optional[float] = None, - ) -> None: - """ - Initialize a MetricTokenAggregationResult object. - - :param str key: (optional) The content of the **natural_language_query** - parameter used in the query that this result represents. - :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated - events divided by the total number of queries currently stored (queries and - events are stored in the log for 30 days). - """ - self.key = key - self.matching_results = matching_results - self.event_rate = event_rate - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregationResult': - """Initialize a MetricTokenAggregationResult object from a json dictionary.""" - args = {} - if (key := _dict.get('key')) is not None: - args['key'] = key - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - if (event_rate := _dict.get('event_rate')) is not None: - args['event_rate'] = event_rate - return cls(**args) - - @classmethod - 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: - _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, 'event_rate') and self.event_rate is not None: - _dict['event_rate'] = self.event_rate - 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 MetricTokenAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'MetricTokenAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricTokenResponse: - """ - The response generated from a call to a **metrics** method that evaluates tokens. - - :param List[MetricTokenAggregation] aggregations: (optional) Array of metric - token aggregations. - """ - - def __init__( - self, - *, - aggregations: Optional[List['MetricTokenAggregation']] = None, - ) -> None: - """ - Initialize a MetricTokenResponse object. - - :param List[MetricTokenAggregation] aggregations: (optional) Array of - metric token aggregations. - """ - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricTokenResponse': - """Initialize a MetricTokenResponse object from a json dictionary.""" - args = {} - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - MetricTokenAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @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: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this MetricTokenResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'MetricTokenResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentConcepts: - """ - An object specifiying the concepts enrichment and related parameters. - - :param int limit: (optional) The maximum number of concepts enrichments to - extact from each instance of the specified field. - """ - - def __init__( - self, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a NluEnrichmentConcepts object. - - :param int limit: (optional) The maximum number of concepts enrichments to - extact from each instance of the specified field. - """ - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentConcepts': - """Initialize a NluEnrichmentConcepts object from a json dictionary.""" - args = {} - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @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 _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: '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: 'NluEnrichmentConcepts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentEmotion: - """ - An object specifying the emotion detection enrichment and related parameters. - - :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 strings - that will have any associated emotions detected. - """ - - def __init__( - self, - *, - document: Optional[bool] = None, - targets: Optional[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 - strings that will have any associated emotions detected. - """ - self.document = document - self.targets = targets - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEmotion': - """Initialize a NluEnrichmentEmotion object from a json dictionary.""" - args = {} - if (document := _dict.get('document')) is not None: - args['document'] = document - if (targets := _dict.get('targets')) is not None: - args['targets'] = targets - return cls(**args) - - @classmethod - 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: - _dict['document'] = self.document - if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = self.targets - 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 NluEnrichmentEmotion object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'NluEnrichmentEmotion') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentEntities: - """ - An object speficying the Entities enrichment and related parameters. - - :param bool sentiment: (optional) When `true`, sentiment analysis of entities - will be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of entities will - be performed on the specified field. - :param int limit: (optional) The maximum number of entities to extract for each - instance of the specified field. - :param bool mentions: (optional) When `true`, the number of mentions of each - identified entity is recorded. The default is `false`. - :param bool mention_types: (optional) When `true`, the types of mentions for - each idetifieid entity is recorded. The default is `false`. - :param bool sentence_locations: (optional) When `true`, a list of sentence - locations for each instance of each identified entity is recorded. The default - is `false`. - :param str model: (optional) The enrichement model to use with entity - extraction. May be a custom model provided by Watson Knowledge Studio, or the - default public model `alchemy`. - """ - - def __init__( - self, - *, - sentiment: Optional[bool] = None, - emotion: Optional[bool] = None, - limit: Optional[int] = None, - mentions: Optional[bool] = None, - mention_types: Optional[bool] = None, - sentence_locations: Optional[bool] = None, - model: Optional[str] = None, - ) -> None: - """ - Initialize a NluEnrichmentEntities object. - - :param bool sentiment: (optional) When `true`, sentiment analysis of - entities will be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of entities - will be performed on the specified field. - :param int limit: (optional) The maximum number of entities to extract for - each instance of the specified field. - :param bool mentions: (optional) When `true`, the number of mentions of - each identified entity is recorded. The default is `false`. - :param bool mention_types: (optional) When `true`, the types of mentions - for each idetifieid entity is recorded. The default is `false`. - :param bool sentence_locations: (optional) When `true`, a list of sentence - locations for each instance of each identified entity is recorded. The - default is `false`. - :param str model: (optional) The enrichement model to use with entity - extraction. May be a custom model provided by Watson Knowledge Studio, or - the default public model `alchemy`. - """ - self.sentiment = sentiment - self.emotion = emotion - self.limit = limit - self.mentions = mentions - self.mention_types = mention_types - self.sentence_locations = sentence_locations - self.model = model - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEntities': - """Initialize a NluEnrichmentEntities object from a json dictionary.""" - args = {} - if (sentiment := _dict.get('sentiment')) is not None: - args['sentiment'] = sentiment - if (emotion := _dict.get('emotion')) is not None: - args['emotion'] = emotion - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - if (mentions := _dict.get('mentions')) is not None: - args['mentions'] = mentions - if (mention_types := _dict.get('mention_types')) is not None: - args['mention_types'] = mention_types - if (sentence_locations := _dict.get('sentence_locations')) is not None: - args['sentence_locations'] = sentence_locations - if (model := _dict.get('model')) is not None: - args['model'] = model - return cls(**args) - - @classmethod - 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: - _dict['sentiment'] = self.sentiment - if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = self.mentions - if hasattr(self, 'mention_types') and self.mention_types is not None: - _dict['mention_types'] = self.mention_types - if hasattr( - self, - 'sentence_locations') and self.sentence_locations is not None: - _dict['sentence_locations'] = self.sentence_locations - if hasattr(self, 'model') and self.model is not None: - _dict['model'] = self.model - 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 NluEnrichmentEntities object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'NluEnrichmentEntities') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentFeatures: - """ - Object containing Natural Language Understanding features to be used. - - :param NluEnrichmentKeywords keywords: (optional) An object specifying the - Keyword enrichment and related parameters. - :param NluEnrichmentEntities entities: (optional) An object speficying the - Entities enrichment and related parameters. - :param NluEnrichmentSentiment sentiment: (optional) An object specifying the - sentiment extraction enrichment and related parameters. - :param NluEnrichmentEmotion emotion: (optional) An object specifying the emotion - detection enrichment and related parameters. - :param dict categories: (optional) An object that indicates the Categories - enrichment will be applied to the specified field. - :param NluEnrichmentSemanticRoles semantic_roles: (optional) An object - specifiying the semantic roles enrichment and related parameters. - :param NluEnrichmentRelations relations: (optional) An object specifying the - relations enrichment and related parameters. - :param NluEnrichmentConcepts concepts: (optional) An object specifiying the - concepts enrichment and related parameters. - """ - - def __init__( - self, - *, - keywords: Optional['NluEnrichmentKeywords'] = None, - entities: Optional['NluEnrichmentEntities'] = None, - sentiment: Optional['NluEnrichmentSentiment'] = None, - emotion: Optional['NluEnrichmentEmotion'] = None, - categories: Optional[dict] = None, - semantic_roles: Optional['NluEnrichmentSemanticRoles'] = None, - relations: Optional['NluEnrichmentRelations'] = None, - concepts: Optional['NluEnrichmentConcepts'] = None, - ) -> None: - """ - Initialize a NluEnrichmentFeatures object. - - :param NluEnrichmentKeywords keywords: (optional) An object specifying the - Keyword enrichment and related parameters. - :param NluEnrichmentEntities entities: (optional) An object speficying the - Entities enrichment and related parameters. - :param NluEnrichmentSentiment sentiment: (optional) An object specifying - the sentiment extraction enrichment and related parameters. - :param NluEnrichmentEmotion emotion: (optional) An object specifying the - emotion detection enrichment and related parameters. - :param dict categories: (optional) An object that indicates the Categories - enrichment will be applied to the specified field. - :param NluEnrichmentSemanticRoles semantic_roles: (optional) An object - specifiying the semantic roles enrichment and related parameters. - :param NluEnrichmentRelations relations: (optional) An object specifying - the relations enrichment and related parameters. - :param NluEnrichmentConcepts concepts: (optional) An object specifiying the - concepts enrichment and related parameters. - """ - self.keywords = keywords - self.entities = entities - self.sentiment = sentiment - self.emotion = emotion - self.categories = categories - self.semantic_roles = semantic_roles - self.relations = relations - self.concepts = concepts - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentFeatures': - """Initialize a NluEnrichmentFeatures object from a json dictionary.""" - args = {} - if (keywords := _dict.get('keywords')) is not None: - args['keywords'] = NluEnrichmentKeywords.from_dict(keywords) - if (entities := _dict.get('entities')) is not None: - args['entities'] = NluEnrichmentEntities.from_dict(entities) - if (sentiment := _dict.get('sentiment')) is not None: - args['sentiment'] = NluEnrichmentSentiment.from_dict(sentiment) - if (emotion := _dict.get('emotion')) is not None: - args['emotion'] = NluEnrichmentEmotion.from_dict(emotion) - if (categories := _dict.get('categories')) is not None: - args['categories'] = categories - if (semantic_roles := _dict.get('semantic_roles')) is not None: - args['semantic_roles'] = NluEnrichmentSemanticRoles.from_dict( - semantic_roles) - if (relations := _dict.get('relations')) is not None: - args['relations'] = NluEnrichmentRelations.from_dict(relations) - if (concepts := _dict.get('concepts')) is not None: - args['concepts'] = NluEnrichmentConcepts.from_dict(concepts) - return cls(**args) - - @classmethod - 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: - if isinstance(self.keywords, dict): - _dict['keywords'] = self.keywords - else: - _dict['keywords'] = self.keywords.to_dict() - if hasattr(self, 'entities') and self.entities is not None: - if isinstance(self.entities, dict): - _dict['entities'] = self.entities - else: - _dict['entities'] = self.entities.to_dict() - if hasattr(self, 'sentiment') and self.sentiment is not None: - if isinstance(self.sentiment, dict): - _dict['sentiment'] = self.sentiment - else: - _dict['sentiment'] = self.sentiment.to_dict() - if hasattr(self, 'emotion') and self.emotion is not None: - if isinstance(self.emotion, dict): - _dict['emotion'] = self.emotion - else: - _dict['emotion'] = self.emotion.to_dict() - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = self.categories - if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - if isinstance(self.semantic_roles, dict): - _dict['semantic_roles'] = self.semantic_roles - else: - _dict['semantic_roles'] = self.semantic_roles.to_dict() - if hasattr(self, 'relations') and self.relations is not None: - if isinstance(self.relations, dict): - _dict['relations'] = self.relations - else: - _dict['relations'] = self.relations.to_dict() - if hasattr(self, 'concepts') and self.concepts is not None: - if isinstance(self.concepts, dict): - _dict['concepts'] = self.concepts - else: - _dict['concepts'] = self.concepts.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 NluEnrichmentFeatures object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'NluEnrichmentFeatures') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentKeywords: - """ - An object specifying the Keyword enrichment and related parameters. - - :param bool sentiment: (optional) When `true`, sentiment analysis of keywords - will be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of keywords will - be performed on the specified field. - :param int limit: (optional) The maximum number of keywords to extract for each - instance of the specified field. - """ - - def __init__( - self, - *, - sentiment: Optional[bool] = None, - emotion: Optional[bool] = None, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a NluEnrichmentKeywords object. - - :param bool sentiment: (optional) When `true`, sentiment analysis of - keywords will be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of keywords - will be performed on the specified field. - :param int limit: (optional) The maximum number of keywords to extract for - each instance of the specified field. - """ - self.sentiment = sentiment - self.emotion = emotion - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentKeywords': - """Initialize a NluEnrichmentKeywords object from a json dictionary.""" - args = {} - if (sentiment := _dict.get('sentiment')) is not None: - args['sentiment'] = sentiment - if (emotion := _dict.get('emotion')) is not None: - args['emotion'] = emotion - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @classmethod - 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: - _dict['sentiment'] = self.sentiment - if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 NluEnrichmentKeywords object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'NluEnrichmentKeywords') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentRelations: - """ - An object specifying the relations enrichment and related parameters. - - :param str model: (optional) *For use with `natural_language_understanding` - enrichments only.* The enrichement model to use with relationship extraction. - May be a custom model provided by Watson Knowledge Studio, the default public - model is`en-news`. - """ - - def __init__( - self, - *, - model: Optional[str] = None, - ) -> None: - """ - Initialize a NluEnrichmentRelations object. - - :param str model: (optional) *For use with `natural_language_understanding` - enrichments only.* The enrichement model to use with relationship - extraction. May be a custom model provided by Watson Knowledge Studio, the - default public model is`en-news`. - """ - self.model = model - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentRelations': - """Initialize a NluEnrichmentRelations object from a json dictionary.""" - args = {} - if (model := _dict.get('model')) is not None: - args['model'] = model - return cls(**args) - - @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 _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: '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: 'NluEnrichmentRelations') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentSemanticRoles: - """ - An object specifiying the semantic roles enrichment and related parameters. - - :param bool entities: (optional) When `true`, entities are extracted from the - identified sentence parts. - :param bool keywords: (optional) When `true`, keywords are extracted from the - identified sentence parts. - :param int limit: (optional) The maximum number of semantic roles enrichments to - extact from each instance of the specified field. - """ - - def __init__( - self, - *, - entities: Optional[bool] = None, - keywords: Optional[bool] = None, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a NluEnrichmentSemanticRoles object. - - :param bool entities: (optional) When `true`, entities are extracted from - the identified sentence parts. - :param bool keywords: (optional) When `true`, keywords are extracted from - the identified sentence parts. - :param int limit: (optional) The maximum number of semantic roles - enrichments to extact from each instance of the specified field. - """ - self.entities = entities - self.keywords = keywords - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSemanticRoles': - """Initialize a NluEnrichmentSemanticRoles object from a json dictionary.""" - args = {} - if (entities := _dict.get('entities')) is not None: - args['entities'] = entities - if (keywords := _dict.get('keywords')) is not None: - args['keywords'] = keywords - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @classmethod - 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: - _dict['entities'] = self.entities - if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = self.keywords - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 NluEnrichmentSemanticRoles object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'NluEnrichmentSemanticRoles') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentSentiment: - """ - An object specifying the sentiment extraction enrichment and related parameters. - - :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 strings - that will have any associated sentiment analyzed. - """ - - def __init__( - self, - *, - document: Optional[bool] = None, - targets: Optional[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 - strings that will have any associated sentiment analyzed. - """ - self.document = document - self.targets = targets - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSentiment': - """Initialize a NluEnrichmentSentiment object from a json dictionary.""" - args = {} - if (document := _dict.get('document')) is not None: - args['document'] = document - if (targets := _dict.get('targets')) is not None: - args['targets'] = targets - return cls(**args) - - @classmethod - 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: - _dict['document'] = self.document - if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = self.targets - 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 NluEnrichmentSentiment object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'NluEnrichmentSentiment') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NormalizationOperation: - """ - Object containing normalization operations. - - :param str operation: (optional) Identifies what type of operation to perform. - **copy** - Copies the value of the **source_field** to the **destination_field** - field. If the **destination_field** already exists, then the value of the - **source_field** overwrites the original value of the **destination_field**. - **move** - Renames (moves) the **source_field** to the **destination_field**. If - the **destination_field** already exists, then the value of the **source_field** - overwrites the original value of the **destination_field**. Rename is identical - to copy, except that the **source_field** is removed after the value has been - copied to the **destination_field** (it is the same as a _copy_ followed by a - _remove_). - **merge** - Merges the value of the **source_field** with the value of the - **destination_field**. The **destination_field** is converted into an array if - it is not already an array, and the value of the **source_field** is appended to - the array. This operation removes the **source_field** after the merge. If the - **source_field** does not exist in the current document, then the - **destination_field** is still converted into an array (if it is not an array - already). This conversion ensures the type for **destination_field** is - consistent across all documents. - **remove** - Deletes the **source_field** field. The **destination_field** is - ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the - ingested document. **source_field** and **destination_field** are ignored by - this operation because _remove_nulls_ operates on the entire ingested document. - Typically, **remove_nulls** is invoked as the last normalization operation (if - it is invoked at all, it can be time-expensive). - :param str source_field: (optional) The source field for the operation. - :param str destination_field: (optional) The destination field for the - operation. - """ - - def __init__( - self, - *, - operation: Optional[str] = None, - source_field: Optional[str] = None, - destination_field: Optional[str] = None, - ) -> None: - """ - Initialize a NormalizationOperation object. - - :param str operation: (optional) Identifies what type of operation to - perform. - **copy** - Copies the value of the **source_field** to the - **destination_field** field. If the **destination_field** already exists, - then the value of the **source_field** overwrites the original value of the - **destination_field**. - **move** - Renames (moves) the **source_field** to the - **destination_field**. If the **destination_field** already exists, then - the value of the **source_field** overwrites the original value of the - **destination_field**. Rename is identical to copy, except that the - **source_field** is removed after the value has been copied to the - **destination_field** (it is the same as a _copy_ followed by a _remove_). - **merge** - Merges the value of the **source_field** with the value of the - **destination_field**. The **destination_field** is converted into an array - if it is not already an array, and the value of the **source_field** is - appended to the array. This operation removes the **source_field** after - the merge. If the **source_field** does not exist in the current document, - then the **destination_field** is still converted into an array (if it is - not an array already). This conversion ensures the type for - **destination_field** is consistent across all documents. - **remove** - Deletes the **source_field** field. The **destination_field** - is ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the - ingested document. **source_field** and **destination_field** are ignored - by this operation because _remove_nulls_ operates on the entire ingested - document. Typically, **remove_nulls** is invoked as the last normalization - operation (if it is invoked at all, it can be time-expensive). - :param str source_field: (optional) The source field for the operation. - :param str destination_field: (optional) The destination field for the - operation. - """ - self.operation = operation - self.source_field = source_field - self.destination_field = destination_field - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NormalizationOperation': - """Initialize a NormalizationOperation object from a json dictionary.""" - args = {} - if (operation := _dict.get('operation')) is not None: - args['operation'] = operation - if (source_field := _dict.get('source_field')) is not None: - args['source_field'] = source_field - if (destination_field := _dict.get('destination_field')) is not None: - args['destination_field'] = destination_field - return cls(**args) - - @classmethod - 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: - _dict['operation'] = self.operation - if hasattr(self, 'source_field') and self.source_field is not None: - _dict['source_field'] = self.source_field - if hasattr(self, - 'destination_field') and self.destination_field is not None: - _dict['destination_field'] = self.destination_field - 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 NormalizationOperation object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'NormalizationOperation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class OperationEnum(str, Enum): - """ - Identifies what type of operation to perform. - **copy** - Copies the value of the **source_field** to the **destination_field** - field. If the **destination_field** already exists, then the value of the - **source_field** overwrites the original value of the **destination_field**. - **move** - Renames (moves) the **source_field** to the **destination_field**. If - the **destination_field** already exists, then the value of the **source_field** - overwrites the original value of the **destination_field**. Rename is identical to - copy, except that the **source_field** is removed after the value has been copied - to the **destination_field** (it is the same as a _copy_ followed by a _remove_). - **merge** - Merges the value of the **source_field** with the value of the - **destination_field**. The **destination_field** is converted into an array if it - is not already an array, and the value of the **source_field** is appended to the - array. This operation removes the **source_field** after the merge. If the - **source_field** does not exist in the current document, then the - **destination_field** is still converted into an array (if it is not an array - already). This conversion ensures the type for **destination_field** is consistent - across all documents. - **remove** - Deletes the **source_field** field. The **destination_field** is - ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the ingested - document. **source_field** and **destination_field** are ignored by this operation - because _remove_nulls_ operates on the entire ingested document. Typically, - **remove_nulls** is invoked as the last normalization operation (if it is invoked - at all, it can be time-expensive). - """ - - COPY = 'copy' - MOVE = 'move' - MERGE = 'merge' - REMOVE = 'remove' - REMOVE_NULLS = 'remove_nulls' - - -class Notice: - """ - A notice produced for the collection. - - :param str notice_id: (optional) Identifies the notice. Many notices might have - the same ID. This field exists so that user applications can programmatically - identify a notice and take automatic corrective action. Typical notice IDs - include: `index_failed`, `index_failed_too_many_requests`, - `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, - `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, - `missing_model`, `unsupported_model`, - `smart_document_understanding_failed_incompatible_field`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_warning`, - `smart_document_understanding_page_error`, - `smart_document_understanding_page_warning`. **Note:** This is not a complete - list; other values might be returned. - :param datetime created: (optional) The creation date of the collection in the - format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param str document_id: (optional) Unique identifier of the document. - :param str query_id: (optional) Unique identifier of the query used for - relevance training. - :param str severity: (optional) Severity level of the notice. - :param str step: (optional) Ingestion or training step in which the notice - occurred. Typical step values include: `smartDocumentUnderstanding`, - `ingestion`, `indexing`, `convert`. **Note:** This is not a complete list; other - values might be returned. - :param str description: (optional) The description of the notice. - """ - - def __init__( - self, - *, - notice_id: Optional[str] = None, - created: Optional[datetime] = None, - document_id: Optional[str] = None, - query_id: Optional[str] = None, - severity: Optional[str] = None, - step: Optional[str] = None, - description: Optional[str] = None, - ) -> None: - """ - Initialize a Notice object. - - """ - self.notice_id = notice_id - self.created = created - self.document_id = document_id - self.query_id = query_id - self.severity = severity - self.step = step - self.description = description - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Notice': - """Initialize a Notice object from a json dictionary.""" - args = {} - if (notice_id := _dict.get('notice_id')) is not None: - args['notice_id'] = notice_id - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (query_id := _dict.get('query_id')) is not None: - args['query_id'] = query_id - if (severity := _dict.get('severity')) is not None: - args['severity'] = severity - if (step := _dict.get('step')) is not None: - args['step'] = step - if (description := _dict.get('description')) is not None: - args['description'] = description - return cls(**args) - - @classmethod - 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 getattr(self, - 'notice_id') is not None: - _dict['notice_id'] = getattr(self, 'notice_id') - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'document_id') and getattr(self, - 'document_id') is not None: - _dict['document_id'] = getattr(self, 'document_id') - if hasattr(self, 'query_id') and getattr(self, 'query_id') is not None: - _dict['query_id'] = getattr(self, 'query_id') - if hasattr(self, 'severity') and getattr(self, 'severity') is not None: - _dict['severity'] = getattr(self, 'severity') - if hasattr(self, 'step') and getattr(self, 'step') is not None: - _dict['step'] = getattr(self, 'step') - if hasattr(self, 'description') and getattr(self, - 'description') is not None: - _dict['description'] = getattr(self, 'description') - 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 Notice object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Notice') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class SeverityEnum(str, Enum): - """ - Severity level of the notice. - """ - - WARNING = 'warning' - ERROR = 'error' - - -class PdfHeadingDetection: - """ - Object containing heading detection conversion settings for PDF documents. - - :param List[FontSetting] fonts: (optional) Array of font matching - configurations. - """ - - def __init__( - self, - *, - fonts: Optional[List['FontSetting']] = None, - ) -> None: - """ - Initialize a PdfHeadingDetection object. - - :param List[FontSetting] fonts: (optional) Array of font matching - configurations. - """ - self.fonts = fonts - - @classmethod - def from_dict(cls, _dict: Dict) -> 'PdfHeadingDetection': - """Initialize a PdfHeadingDetection object from a json dictionary.""" - args = {} - if (fonts := _dict.get('fonts')) is not None: - args['fonts'] = [FontSetting.from_dict(v) for v in fonts] - return cls(**args) - - @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: - fonts_list = [] - for v in self.fonts: - if isinstance(v, dict): - fonts_list.append(v) - else: - fonts_list.append(v.to_dict()) - _dict['fonts'] = fonts_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this PdfHeadingDetection object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'PdfHeadingDetection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class PdfSettings: - """ - A list of PDF conversion settings. - - :param PdfHeadingDetection heading: (optional) Object containing heading - detection conversion settings for PDF documents. - """ - - def __init__( - self, - *, - heading: Optional['PdfHeadingDetection'] = None, - ) -> None: - """ - Initialize a PdfSettings object. - - :param PdfHeadingDetection heading: (optional) Object containing heading - detection conversion settings for PDF documents. - """ - self.heading = heading - - @classmethod - def from_dict(cls, _dict: Dict) -> 'PdfSettings': - """Initialize a PdfSettings object from a json dictionary.""" - args = {} - if (heading := _dict.get('heading')) is not None: - args['heading'] = PdfHeadingDetection.from_dict(heading) - return cls(**args) - - @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: - if isinstance(self.heading, dict): - _dict['heading'] = self.heading - else: - _dict['heading'] = self.heading.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 PdfSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'PdfSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryAggregation: - """ - An aggregation produced by Discovery to analyze the input provided. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - """ - - def __init__( - self, - type: str, - ) -> None: - """ - Initialize a QueryAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - """ - self.type = type - - @classmethod - 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 = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryAggregation JSON' - ) - return cls(**args) - - @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 _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: '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: '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'] = 'QueryHistogramAggregation' - mapping['max'] = 'QueryCalculationAggregation' - mapping['min'] = 'QueryCalculationAggregation' - mapping['average'] = 'QueryCalculationAggregation' - mapping['sum'] = 'QueryCalculationAggregation' - mapping['unique_count'] = 'QueryCalculationAggregation' - mapping['term'] = 'QueryTermAggregation' - mapping['filter'] = 'QueryFilterAggregation' - mapping['nested'] = 'QueryNestedAggregation' - mapping['timeslice'] = 'QueryTimesliceAggregation' - 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 QueryHistogramAggregationResult: - """ - Histogram numeric interval result. - - :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. - """ - - def __init__( - self, - key: int, - matching_results: int, - *, - aggregations: Optional[List['QueryAggregation']] = None, - ) -> 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: Dict) -> 'QueryHistogramAggregationResult': - """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" - args = {} - if (key := _dict.get('key')) is not None: - args['key'] = key - else: - raise ValueError( - 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' - ) - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' - ) - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @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, '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: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryHistogramAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'QueryHistogramAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNoticesResponse: - """ - Object containing notice query results. - - :param int matching_results: (optional) The number of matching results. - :param List[QueryNoticesResult] results: (optional) Array of document results - that match the query. - :param List[QueryAggregation] aggregations: (optional) Array of aggregation - results that match the query. - :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. - """ - - def __init__( - self, - *, - matching_results: Optional[int] = None, - results: Optional[List['QueryNoticesResult']] = None, - aggregations: Optional[List['QueryAggregation']] = None, - passages: Optional[List['QueryPassages']] = None, - duplicates_removed: Optional[int] = None, - ) -> None: - """ - Initialize a QueryNoticesResponse object. - - :param int matching_results: (optional) The number of matching results. - :param List[QueryNoticesResult] results: (optional) Array of document - results that match the query. - :param List[QueryAggregation] aggregations: (optional) Array of aggregation - results that match the query. - :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. - """ - self.matching_results = matching_results - self.results = results - self.aggregations = aggregations - self.passages = passages - self.duplicates_removed = duplicates_removed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': - """Initialize a QueryNoticesResponse object from a json dictionary.""" - args = {} - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - if (results := _dict.get('results')) is not None: - args['results'] = [QueryNoticesResult.from_dict(v) for v in results] - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - if (passages := _dict.get('passages')) is not None: - args['passages'] = [QueryPassages.from_dict(v) for v in passages] - if (duplicates_removed := _dict.get('duplicates_removed')) is not None: - args['duplicates_removed'] = duplicates_removed - return cls(**args) - - @classmethod - 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, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - if hasattr(self, 'passages') and self.passages is not None: - passages_list = [] - for v in self.passages: - if isinstance(v, dict): - passages_list.append(v) - else: - passages_list.append(v.to_dict()) - _dict['passages'] = passages_list - if hasattr( - self, - 'duplicates_removed') and self.duplicates_removed is not None: - _dict['duplicates_removed'] = self.duplicates_removed - 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 QueryNoticesResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'QueryNoticesResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNoticesResult: - """ - Query result object. - - :param str id: (optional) The unique identifier of the document. - :param dict metadata: (optional) Metadata of the document. - :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - :param int code: (optional) The internal status code returned by the ingestion - subsystem indicating the overall result of ingesting the source document. - :param str filename: (optional) Name of the original source file (if available). - :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file - (formatted as a hexadecimal string). - :param List[Notice] notices: (optional) Array of notices for the document. - """ - - # The set of defined properties for the class - _properties = frozenset([ - 'id', 'metadata', 'collection_id', 'result_metadata', 'code', - 'filename', 'file_type', 'sha1', 'notices' - ]) - - def __init__( - self, - *, - id: Optional[str] = None, - metadata: Optional[dict] = None, - collection_id: Optional[str] = None, - result_metadata: Optional['QueryResultMetadata'] = None, - code: Optional[int] = None, - filename: Optional[str] = None, - file_type: Optional[str] = None, - sha1: Optional[str] = None, - notices: Optional[List['Notice']] = None, - **kwargs, - ) -> None: - """ - Initialize a QueryNoticesResult object. - - :param str id: (optional) The unique identifier of the document. - :param dict metadata: (optional) Metadata of the document. - :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - :param int code: (optional) The internal status code returned by the - ingestion subsystem indicating the overall result of ingesting the source - document. - :param str filename: (optional) Name of the original source file (if - available). - :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file - (formatted as a hexadecimal string). - :param List[Notice] notices: (optional) Array of notices for the document. - :param **kwargs: (optional) Any additional properties. - """ - self.id = id - self.metadata = metadata - self.collection_id = collection_id - self.result_metadata = result_metadata - self.code = code - self.filename = filename - self.file_type = file_type - self.sha1 = sha1 - self.notices = notices - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryNoticesResult': - """Initialize a QueryNoticesResult object from a json dictionary.""" - args = {} - if (id := _dict.get('id')) is not None: - args['id'] = id - if (metadata := _dict.get('metadata')) is not None: - args['metadata'] = metadata - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - if (result_metadata := _dict.get('result_metadata')) is not None: - args['result_metadata'] = QueryResultMetadata.from_dict( - result_metadata) - if (code := _dict.get('code')) is not None: - args['code'] = code - if (filename := _dict.get('filename')) is not None: - args['filename'] = filename - if (file_type := _dict.get('file_type')) is not None: - args['file_type'] = file_type - if (sha1 := _dict.get('sha1')) is not None: - args['sha1'] = sha1 - if (notices := _dict.get('notices')) is not None: - args['notices'] = [Notice.from_dict(v) for v in notices] - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) - return cls(**args) - - @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: - _dict['id'] = self.id - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - if isinstance(self.result_metadata, dict): - _dict['result_metadata'] = self.result_metadata - else: - _dict['result_metadata'] = self.result_metadata.to_dict() - if hasattr(self, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, 'file_type') and self.file_type is not None: - _dict['file_type'] = self.file_type - if hasattr(self, 'sha1') and self.sha1 is not None: - _dict['sha1'] = self.sha1 - if hasattr(self, 'notices') and self.notices is not None: - notices_list = [] - for v in self.notices: - if isinstance(v, dict): - notices_list.append(v) - else: - notices_list.append(v.to_dict()) - _dict['notices'] = notices_list - for _key in [ - k for k in vars(self).keys() - if k not in QueryNoticesResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of QueryNoticesResult""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in QueryNoticesResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of QueryNoticesResult""" - for _key in [ - k for k in vars(self).keys() - if k not in QueryNoticesResult._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in QueryNoticesResult._properties: - setattr(self, _key, _value) - - def __str__(self) -> str: - """Return a `str` version of this QueryNoticesResult object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'QueryNoticesResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class FileTypeEnum(str, Enum): - """ - The type of the original source file. - """ - - PDF = 'pdf' - HTML = 'html' - WORD = 'word' - JSON = 'json' - - -class QueryPassages: - """ - A passage query result. - - :param str document_id: (optional) The unique identifier of the document from - which the passage has been extracted. - :param float passage_score: (optional) The confidence score of the passages's - analysis. A higher score indicates greater confidence. - :param str passage_text: (optional) The content of the extracted passage. - :param int start_offset: (optional) The position of the first character of the - extracted passage in the originating field. - :param int end_offset: (optional) The position of the last character of the - extracted passage in the originating field. - :param str field: (optional) The label of the field from which the passage has - been extracted. - """ - - def __init__( - self, - *, - document_id: Optional[str] = None, - passage_score: Optional[float] = None, - passage_text: Optional[str] = None, - start_offset: Optional[int] = None, - end_offset: Optional[int] = None, - field: Optional[str] = None, - ) -> None: - """ - Initialize a QueryPassages object. - - :param str document_id: (optional) The unique identifier of the document - from which the passage has been extracted. - :param float passage_score: (optional) The confidence score of the - passages's analysis. A higher score indicates greater confidence. - :param str passage_text: (optional) The content of the extracted passage. - :param int start_offset: (optional) The position of the first character of - the extracted passage in the originating field. - :param int end_offset: (optional) The position of the last character of the - extracted passage in the originating field. - :param str field: (optional) The label of the field from which the passage - has been extracted. - """ - self.document_id = document_id - self.passage_score = passage_score - self.passage_text = passage_text - self.start_offset = start_offset - self.end_offset = end_offset - self.field = field - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryPassages': - """Initialize a QueryPassages object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (passage_score := _dict.get('passage_score')) is not None: - args['passage_score'] = passage_score - if (passage_text := _dict.get('passage_text')) is not None: - args['passage_text'] = passage_text - if (start_offset := _dict.get('start_offset')) is not None: - args['start_offset'] = start_offset - if (end_offset := _dict.get('end_offset')) is not None: - args['end_offset'] = end_offset - if (field := _dict.get('field')) is not None: - args['field'] = field - return cls(**args) - - @classmethod - 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: - _dict['document_id'] = self.document_id - if hasattr(self, 'passage_score') and self.passage_score is not None: - _dict['passage_score'] = self.passage_score - if hasattr(self, 'passage_text') and self.passage_text is not None: - _dict['passage_text'] = self.passage_text - if hasattr(self, 'start_offset') and self.start_offset is not None: - _dict['start_offset'] = self.start_offset - if hasattr(self, 'end_offset') and self.end_offset is not None: - _dict['end_offset'] = self.end_offset - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - 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 QueryPassages object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'QueryPassages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryResponse: - """ - A response containing the documents and aggregations for the query. - - :param int matching_results: (optional) The number of matching results for the - query. - :param List[QueryResult] results: (optional) Array of document results for the - query. - :param List[QueryAggregation] aggregations: (optional) Array of aggregation - results for the query. - :param List[QueryPassages] passages: (optional) Array of passage results for the - query. - :param int duplicates_removed: (optional) The number of duplicate results - removed. - :param str session_token: (optional) The session token for this query. The - session token can be used to add events associated with this query to the query - and event log. - **Important:** Session tokens are case sensitive. - :param RetrievalDetails retrieval_details: (optional) An object contain - retrieval type information. - :param str suggested_query: (optional) The suggestions for a misspelled natural - language query. - """ - - def __init__( - self, - *, - matching_results: Optional[int] = None, - results: Optional[List['QueryResult']] = None, - aggregations: Optional[List['QueryAggregation']] = None, - passages: Optional[List['QueryPassages']] = None, - duplicates_removed: Optional[int] = None, - session_token: Optional[str] = None, - retrieval_details: Optional['RetrievalDetails'] = None, - suggested_query: Optional[str] = None, - ) -> None: - """ - Initialize a QueryResponse object. - - :param int matching_results: (optional) The number of matching results for - the query. - :param List[QueryResult] results: (optional) Array of document results for - the query. - :param List[QueryAggregation] aggregations: (optional) Array of aggregation - results for the query. - :param List[QueryPassages] passages: (optional) Array of passage results - for the query. - :param int duplicates_removed: (optional) The number of duplicate results - removed. - :param str session_token: (optional) The session token for this query. The - session token can be used to add events associated with this query to the - query and event log. - **Important:** Session tokens are case sensitive. - :param RetrievalDetails retrieval_details: (optional) An object contain - retrieval type information. - :param str suggested_query: (optional) The suggestions for a misspelled - natural language query. - """ - self.matching_results = matching_results - self.results = results - self.aggregations = aggregations - self.passages = passages - self.duplicates_removed = duplicates_removed - self.session_token = session_token - self.retrieval_details = retrieval_details - self.suggested_query = suggested_query - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryResponse': - """Initialize a QueryResponse object from a json dictionary.""" - args = {} - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - if (results := _dict.get('results')) is not None: - args['results'] = [QueryResult.from_dict(v) for v in results] - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - if (passages := _dict.get('passages')) is not None: - args['passages'] = [QueryPassages.from_dict(v) for v in passages] - if (duplicates_removed := _dict.get('duplicates_removed')) is not None: - args['duplicates_removed'] = duplicates_removed - if (session_token := _dict.get('session_token')) is not None: - args['session_token'] = session_token - if (retrieval_details := _dict.get('retrieval_details')) is not None: - args['retrieval_details'] = RetrievalDetails.from_dict( - retrieval_details) - if (suggested_query := _dict.get('suggested_query')) is not None: - args['suggested_query'] = suggested_query - return cls(**args) - - @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, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - if hasattr(self, 'passages') and self.passages is not None: - passages_list = [] - for v in self.passages: - if isinstance(v, dict): - passages_list.append(v) - else: - passages_list.append(v.to_dict()) - _dict['passages'] = passages_list - if hasattr( - self, - 'duplicates_removed') and self.duplicates_removed is not None: - _dict['duplicates_removed'] = self.duplicates_removed - if hasattr(self, 'session_token') and self.session_token is not None: - _dict['session_token'] = self.session_token - if hasattr(self, - 'retrieval_details') and self.retrieval_details is not None: - if isinstance(self.retrieval_details, dict): - _dict['retrieval_details'] = self.retrieval_details - else: - _dict['retrieval_details'] = self.retrieval_details.to_dict() - if hasattr(self, - 'suggested_query') and self.suggested_query is not None: - _dict['suggested_query'] = self.suggested_query - 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 QueryResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'QueryResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryResult: - """ - Query result object. - - :param str id: (optional) The unique identifier of the document. - :param dict metadata: (optional) Metadata of the document. - :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - """ - - # The set of defined properties for the class - _properties = frozenset( - ['id', 'metadata', 'collection_id', 'result_metadata']) - - def __init__( - self, - *, - id: Optional[str] = None, - metadata: Optional[dict] = None, - collection_id: Optional[str] = None, - result_metadata: Optional['QueryResultMetadata'] = None, - **kwargs, - ) -> None: - """ - Initialize a QueryResult object. - - :param str id: (optional) The unique identifier of the document. - :param dict metadata: (optional) Metadata of the document. - :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - :param **kwargs: (optional) Any additional properties. - """ - self.id = id - self.metadata = metadata - self.collection_id = collection_id - self.result_metadata = result_metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryResult': - """Initialize a QueryResult object from a json dictionary.""" - args = {} - if (id := _dict.get('id')) is not None: - args['id'] = id - if (metadata := _dict.get('metadata')) is not None: - args['metadata'] = metadata - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - if (result_metadata := _dict.get('result_metadata')) is not None: - args['result_metadata'] = QueryResultMetadata.from_dict( - result_metadata) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a 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: - _dict['id'] = self.id - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - if isinstance(self.result_metadata, dict): - _dict['result_metadata'] = self.result_metadata - else: - _dict['result_metadata'] = self.result_metadata.to_dict() - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of QueryResult""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of QueryResult""" - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in QueryResult._properties: - setattr(self, _key, _value) - - def __str__(self) -> str: - """Return a `str` version of this QueryResult object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'QueryResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryResultMetadata: - """ - Metadata of a query result. - - :param float score: An unbounded measure of the relevance of a particular - result, dependent on the query and matching document. A higher score indicates a - greater match to the query parameters. - :param float confidence: (optional) The confidence score for the given result. - Calculated based on how relevant the result is estimated to be. confidence can - range from `0.0` to `1.0`. The higher the number, the more relevant the - document. The `confidence` value for a result was calculated using the model - specified in the `document_retrieval_strategy` field of the result set. - """ - - def __init__( - self, - score: float, - *, - confidence: Optional[float] = None, - ) -> None: - """ - Initialize a QueryResultMetadata object. - - :param float score: An unbounded measure of the relevance of a particular - result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. - :param float confidence: (optional) The confidence score for the given - result. Calculated based on how relevant the result is estimated to be. - confidence can range from `0.0` to `1.0`. The higher the number, the more - relevant the document. The `confidence` value for a result was calculated - using the model specified in the `document_retrieval_strategy` field of the - result set. - """ - self.score = score - self.confidence = confidence - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': - """Initialize a QueryResultMetadata object from a json dictionary.""" - args = {} - if (score := _dict.get('score')) is not None: - args['score'] = score - else: - raise ValueError( - 'Required property \'score\' not present in QueryResultMetadata JSON' - ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - return cls(**args) - - @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: - _dict['score'] = self.score - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - 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 QueryResultMetadata object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'QueryResultMetadata') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTermAggregationResult: - """ - Top value result for the term aggregation. - - :param str key: Value of the field with a non-zero frequency in the document - set. - :param int matching_results: Number of documents that contain the 'key'. - :param float relevancy: (optional) The relevancy for this term. - :param int total_matching_documents: (optional) The number of documents which - have the term as the value of specified field in the whole set of documents in - this collection. Returned only when the `relevancy` parameter is set to `true`. - :param int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned only - when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__( - self, - key: str, - matching_results: int, - *, - relevancy: Optional[float] = None, - total_matching_documents: Optional[int] = None, - estimated_matching_documents: Optional[int] = None, - aggregations: Optional[List['QueryAggregation']] = None, - ) -> None: - """ - Initialize a QueryTermAggregationResult object. - - :param str key: Value of the field with a non-zero frequency in the - document set. - :param int matching_results: Number of documents that contain the 'key'. - :param float relevancy: (optional) The relevancy for this term. - :param int total_matching_documents: (optional) The number of documents - which have the term as the value of specified field in the whole set of - documents in this collection. Returned only when the `relevancy` parameter - is set to `true`. - :param int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned - only when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - self.key = key - self.matching_results = matching_results - self.relevancy = relevancy - self.total_matching_documents = total_matching_documents - self.estimated_matching_documents = estimated_matching_documents - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': - """Initialize a QueryTermAggregationResult object from a json dictionary.""" - args = {} - if (key := _dict.get('key')) is not None: - args['key'] = key - else: - raise ValueError( - 'Required property \'key\' not present in QueryTermAggregationResult JSON' - ) - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' - ) - if (relevancy := _dict.get('relevancy')) is not None: - args['relevancy'] = relevancy - if (total_matching_documents := - _dict.get('total_matching_documents')) is not None: - args['total_matching_documents'] = total_matching_documents - if (estimated_matching_documents := - _dict.get('estimated_matching_documents')) is not None: - args['estimated_matching_documents'] = estimated_matching_documents - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @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: - _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, 'relevancy') and self.relevancy is not None: - _dict['relevancy'] = self.relevancy - if hasattr(self, 'total_matching_documents' - ) and self.total_matching_documents is not None: - _dict['total_matching_documents'] = self.total_matching_documents - if hasattr(self, 'estimated_matching_documents' - ) and self.estimated_matching_documents is not None: - _dict[ - 'estimated_matching_documents'] = self.estimated_matching_documents - if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryTermAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'QueryTermAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTimesliceAggregationResult: - """ - A timeslice interval segment. - - :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. - """ - - def __init__( - self, - key_as_string: str, - key: int, - matching_results: int, - *, - aggregations: Optional[List['QueryAggregation']] = None, - ) -> 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 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.key_as_string = key_as_string - self.key = key - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': - """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" - args = {} - if (key_as_string := _dict.get('key_as_string')) is not None: - args['key_as_string'] = key_as_string - else: - raise ValueError( - 'Required property \'key_as_string\' not present in QueryTimesliceAggregationResult JSON' - ) - if (key := _dict.get('key')) is not None: - args['key'] = key - else: - raise ValueError( - 'Required property \'key\' not present in QueryTimesliceAggregationResult JSON' - ) - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' - ) - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @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: - _dict['key_as_string'] = self.key_as_string - 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: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this QueryTimesliceAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'QueryTimesliceAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTopHitsAggregationResult: - """ - A query response that contains the matching documents for the preceding aggregations. - - :param int matching_results: Number of matching results. - :param List[dict] hits: (optional) An array of the document results. - """ - - def __init__( - self, - matching_results: int, - *, - hits: Optional[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. - """ - self.matching_results = matching_results - self.hits = hits - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': - """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" - args = {} - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryTopHitsAggregationResult JSON' - ) - if (hits := _dict.get('hits')) is not None: - args['hits'] = hits - return cls(**args) - - @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, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits - 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 QueryTopHitsAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'QueryTopHitsAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class RetrievalDetails: - """ - An object contain retrieval type information. - - :param str document_retrieval_strategy: (optional) Indentifies the document - retrieval strategy used for this query. `relevancy_training` indicates that the - results were returned using a relevancy trained model. - `continuous_relevancy_training` indicates that the results were returned using - the continuous relevancy training model created by result feedback analysis. - `untrained` means the results were returned using the standard untrained model. - **Note**: In the event of trained collections being queried, but the trained - model is not used to return results, the **document_retrieval_strategy** will be - listed as `untrained`. - """ - - def __init__( - self, - *, - document_retrieval_strategy: Optional[str] = None, - ) -> None: - """ - Initialize a RetrievalDetails object. - - :param str document_retrieval_strategy: (optional) Indentifies the document - retrieval strategy used for this query. `relevancy_training` indicates that - the results were returned using a relevancy trained model. - `continuous_relevancy_training` indicates that the results were returned - using the continuous relevancy training model created by result feedback - analysis. `untrained` means the results were returned using the standard - untrained model. - **Note**: In the event of trained collections being queried, but the - trained model is not used to return results, the - **document_retrieval_strategy** will be listed as `untrained`. - """ - self.document_retrieval_strategy = document_retrieval_strategy - - @classmethod - def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': - """Initialize a RetrievalDetails object from a json dictionary.""" - args = {} - if (document_retrieval_strategy := - _dict.get('document_retrieval_strategy')) is not None: - args['document_retrieval_strategy'] = document_retrieval_strategy - return cls(**args) - - @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' - ) and self.document_retrieval_strategy is not None: - _dict[ - 'document_retrieval_strategy'] = self.document_retrieval_strategy - 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 RetrievalDetails object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'RetrievalDetails') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class DocumentRetrievalStrategyEnum(str, Enum): - """ - Indentifies the document retrieval strategy used for this query. - `relevancy_training` indicates that the results were returned using a relevancy - trained model. `continuous_relevancy_training` indicates that the results were - returned using the continuous relevancy training model created by result feedback - analysis. `untrained` means the results were returned using the standard untrained - model. - **Note**: In the event of trained collections being queried, but the trained - model is not used to return results, the **document_retrieval_strategy** will be - listed as `untrained`. - """ - - UNTRAINED = 'untrained' - RELEVANCY_TRAINING = 'relevancy_training' - CONTINUOUS_RELEVANCY_TRAINING = 'continuous_relevancy_training' - - -class SduStatus: - """ - Object containing smart document understanding information for this collection. - - :param bool enabled: (optional) When `true`, smart document understanding - conversion is enabled for this collection. All collections created with a - version date after `2019-04-30` have smart document understanding enabled. If - `false`, documents added to the collection are converted using the - **conversion** settings specified in the configuration associated with the - collection. - :param int total_annotated_pages: (optional) The total number of pages annotated - using smart document understanding in this collection. - :param int total_pages: (optional) The current number of pages that can be used - for training smart document understanding. The `total_pages` number is - calculated as the total number of pages identified from the documents listed in - the **total_documents** field. - :param int total_documents: (optional) The total number of documents in this - collection that can be used to train smart document understanding. For **lite** - plan collections, the maximum is the first 20 uploaded documents (not including - HTML or JSON documents). For other plans, the maximum is the first 40 uploaded - documents (not including HTML or JSON documents). When the maximum is reached, - additional documents uploaded to the collection are not considered for training - smart document understanding. - :param SduStatusCustomFields custom_fields: (optional) Information about custom - smart document understanding fields that exist in this collection. - """ - - def __init__( - self, - *, - enabled: Optional[bool] = None, - total_annotated_pages: Optional[int] = None, - total_pages: Optional[int] = None, - total_documents: Optional[int] = None, - custom_fields: Optional['SduStatusCustomFields'] = None, - ) -> None: - """ - Initialize a SduStatus object. - - :param bool enabled: (optional) When `true`, smart document understanding - conversion is enabled for this collection. All collections created with a - version date after `2019-04-30` have smart document understanding enabled. - If `false`, documents added to the collection are converted using the - **conversion** settings specified in the configuration associated with the - collection. - :param int total_annotated_pages: (optional) The total number of pages - annotated using smart document understanding in this collection. - :param int total_pages: (optional) The current number of pages that can be - used for training smart document understanding. The `total_pages` number is - calculated as the total number of pages identified from the documents - listed in the **total_documents** field. - :param int total_documents: (optional) The total number of documents in - this collection that can be used to train smart document understanding. For - **lite** plan collections, the maximum is the first 20 uploaded documents - (not including HTML or JSON documents). For other plans, the maximum is the - first 40 uploaded documents (not including HTML or JSON documents). When - the maximum is reached, additional documents uploaded to the collection are - not considered for training smart document understanding. - :param SduStatusCustomFields custom_fields: (optional) Information about - custom smart document understanding fields that exist in this collection. - """ - self.enabled = enabled - self.total_annotated_pages = total_annotated_pages - self.total_pages = total_pages - self.total_documents = total_documents - self.custom_fields = custom_fields - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SduStatus': - """Initialize a SduStatus object from a json dictionary.""" - args = {} - if (enabled := _dict.get('enabled')) is not None: - args['enabled'] = enabled - if (total_annotated_pages := - _dict.get('total_annotated_pages')) is not None: - args['total_annotated_pages'] = total_annotated_pages - if (total_pages := _dict.get('total_pages')) is not None: - args['total_pages'] = total_pages - if (total_documents := _dict.get('total_documents')) is not None: - args['total_documents'] = total_documents - if (custom_fields := _dict.get('custom_fields')) is not None: - args['custom_fields'] = SduStatusCustomFields.from_dict( - custom_fields) - return cls(**args) - - @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: - _dict['enabled'] = self.enabled - if hasattr(self, 'total_annotated_pages' - ) and self.total_annotated_pages is not None: - _dict['total_annotated_pages'] = self.total_annotated_pages - if hasattr(self, 'total_pages') and self.total_pages is not None: - _dict['total_pages'] = self.total_pages - if hasattr(self, - 'total_documents') and self.total_documents is not None: - _dict['total_documents'] = self.total_documents - if hasattr(self, 'custom_fields') and self.custom_fields is not None: - if isinstance(self.custom_fields, dict): - _dict['custom_fields'] = self.custom_fields - else: - _dict['custom_fields'] = self.custom_fields.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 SduStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SduStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SduStatusCustomFields: - """ - Information about custom smart document understanding fields that exist in this - collection. - - :param int defined: (optional) The number of custom fields defined for this - collection. - :param int maximum_allowed: (optional) The maximum number of custom fields that - are allowed in this collection. - """ - - def __init__( - self, - *, - defined: Optional[int] = None, - maximum_allowed: Optional[int] = None, - ) -> None: - """ - Initialize a SduStatusCustomFields object. - - :param int defined: (optional) The number of custom fields defined for this - collection. - :param int maximum_allowed: (optional) The maximum number of custom fields - that are allowed in this collection. - """ - self.defined = defined - self.maximum_allowed = maximum_allowed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SduStatusCustomFields': - """Initialize a SduStatusCustomFields object from a json dictionary.""" - args = {} - if (defined := _dict.get('defined')) is not None: - args['defined'] = defined - if (maximum_allowed := _dict.get('maximum_allowed')) is not None: - args['maximum_allowed'] = maximum_allowed - return cls(**args) - - @classmethod - 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, - 'maximum_allowed') and self.maximum_allowed is not None: - _dict['maximum_allowed'] = self.maximum_allowed - 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 SduStatusCustomFields object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SduStatusCustomFields') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SearchStatus: - """ - Information about the Continuous Relevancy Training for this environment. - - :param str scope: (optional) Current scope of the training. Always returned as - `environment`. - :param str status: (optional) The current status of Continuous Relevancy - Training for this environment. - :param str status_description: (optional) Long description of the current - Continuous Relevancy Training status. - :param date last_trained: (optional) The date stamp of the most recent completed - training for this environment. - """ - - def __init__( - self, - *, - scope: Optional[str] = None, - status: Optional[str] = None, - status_description: Optional[str] = None, - last_trained: Optional[date] = None, - ) -> None: - """ - Initialize a SearchStatus object. - - :param str scope: (optional) Current scope of the training. Always returned - as `environment`. - :param str status: (optional) The current status of Continuous Relevancy - Training for this environment. - :param str status_description: (optional) Long description of the current - Continuous Relevancy Training status. - :param date last_trained: (optional) The date stamp of the most recent - completed training for this environment. - """ - self.scope = scope - self.status = status - self.status_description = status_description - self.last_trained = last_trained - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchStatus': - """Initialize a SearchStatus object from a json dictionary.""" - args = {} - if (scope := _dict.get('scope')) is not None: - args['scope'] = scope - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (last_trained := _dict.get('last_trained')) is not None: - args['last_trained'] = string_to_date(last_trained) - return cls(**args) - - @classmethod - 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: - _dict['scope'] = self.scope - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr( - self, - 'status_description') and self.status_description is not None: - _dict['status_description'] = self.status_description - if hasattr(self, 'last_trained') and self.last_trained is not None: - _dict['last_trained'] = date_to_string(self.last_trained) - 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 SearchStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SearchStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The current status of Continuous Relevancy Training for this environment. - """ - - NO_DATA = 'NO_DATA' - INSUFFICENT_DATA = 'INSUFFICENT_DATA' - TRAINING = 'TRAINING' - TRAINED = 'TRAINED' - NOT_APPLICABLE = 'NOT_APPLICABLE' - - -class SegmentSettings: - """ - A list of Document Segmentation settings. - - :param bool enabled: (optional) Enables/disables the Document Segmentation - feature. - :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 - document understanding fields that the document is split on. The content of the - annotated field that the segmentation splits at is used as the **title** field - for that segmented result. For example, if the field `sub-title` is specified, - when a document is uploaded each time the smart document understanding - conversion encounters a field of type `sub-title` the document is split at that - point and the content of the field used as the title of the remaining content. - This split is performed for all instances of the listed fields in the uploaded - document. Only valid if used with a collection that has **enabled** set to - `true` in the **smart_document_understanding** object. - """ - - def __init__( - self, - *, - enabled: Optional[bool] = None, - selector_tags: Optional[List[str]] = None, - annotated_fields: Optional[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 - 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 - document understanding fields that the document is split on. The content of - the annotated field that the segmentation splits at is used as the - **title** field for that segmented result. For example, if the field - `sub-title` is specified, when a document is uploaded each time the smart - document understanding conversion encounters a field of type `sub-title` - the document is split at that point and the content of the field used as - the title of the remaining content. This split is performed for all - instances of the listed fields in the uploaded document. Only valid if used - with a collection that has **enabled** set to `true` in the - **smart_document_understanding** object. - """ - self.enabled = enabled - self.selector_tags = selector_tags - self.annotated_fields = annotated_fields - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SegmentSettings': - """Initialize a SegmentSettings object from a json dictionary.""" - args = {} - if (enabled := _dict.get('enabled')) is not None: - args['enabled'] = enabled - if (selector_tags := _dict.get('selector_tags')) is not None: - args['selector_tags'] = selector_tags - if (annotated_fields := _dict.get('annotated_fields')) is not None: - args['annotated_fields'] = annotated_fields - return cls(**args) - - @classmethod - 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: - _dict['enabled'] = self.enabled - if hasattr(self, 'selector_tags') and self.selector_tags is not None: - _dict['selector_tags'] = self.selector_tags - if hasattr(self, - 'annotated_fields') and self.annotated_fields is not None: - _dict['annotated_fields'] = self.annotated_fields - 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 SegmentSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SegmentSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Source: - """ - Object containing source parameters for the configuration. - - :param str type: (optional) The type of source to connect to. - - `box` indicates the configuration is to connect an instance of Enterprise - Box. - - `salesforce` indicates the configuration is to connect to Salesforce. - - `sharepoint` indicates the configuration is to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the configuration is to perform a web page crawl. - - `cloud_object_storage` indicates the configuration is to connect to a cloud - object store. - :param str credential_id: (optional) The **credential_id** of the credentials to - use to connect to the source. Credentials are defined using the **credentials** - method. The **source_type** of the credentials used must match the **type** - field specified in this object. - :param SourceSchedule schedule: (optional) Object containing the schedule - information for the source. - :param SourceOptions options: (optional) The **options** object defines which - items to crawl from the source system. - """ - - def __init__( - self, - *, - type: Optional[str] = None, - credential_id: Optional[str] = None, - schedule: Optional['SourceSchedule'] = None, - options: Optional['SourceOptions'] = None, - ) -> None: - """ - Initialize a Source object. - - :param str type: (optional) The type of source to connect to. - - `box` indicates the configuration is to connect an instance of - Enterprise Box. - - `salesforce` indicates the configuration is to connect to Salesforce. - - `sharepoint` indicates the configuration is to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the configuration is to perform a web page crawl. - - `cloud_object_storage` indicates the configuration is to connect to a - cloud object store. - :param str credential_id: (optional) The **credential_id** of the - credentials to use to connect to the source. Credentials are defined using - the **credentials** method. The **source_type** of the credentials used - must match the **type** field specified in this object. - :param SourceSchedule schedule: (optional) Object containing the schedule - information for the source. - :param SourceOptions options: (optional) The **options** object defines - which items to crawl from the source system. - """ - self.type = type - self.credential_id = credential_id - self.schedule = schedule - self.options = options - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Source': - """Initialize a Source object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (credential_id := _dict.get('credential_id')) is not None: - args['credential_id'] = credential_id - if (schedule := _dict.get('schedule')) is not None: - args['schedule'] = SourceSchedule.from_dict(schedule) - if (options := _dict.get('options')) is not None: - args['options'] = SourceOptions.from_dict(options) - return cls(**args) - - @classmethod - 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: - _dict['type'] = self.type - if hasattr(self, 'credential_id') and self.credential_id is not None: - _dict['credential_id'] = self.credential_id - if hasattr(self, 'schedule') and self.schedule is not None: - if isinstance(self.schedule, dict): - _dict['schedule'] = self.schedule - else: - _dict['schedule'] = self.schedule.to_dict() - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options - else: - _dict['options'] = self.options.to_dict() - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Source object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'Source') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The type of source to connect to. - - `box` indicates the configuration is to connect an instance of Enterprise Box. - - `salesforce` indicates the configuration is to connect to Salesforce. - - `sharepoint` indicates the configuration is to connect to Microsoft SharePoint - Online. - - `web_crawl` indicates the configuration is to perform a web page crawl. - - `cloud_object_storage` indicates the configuration is to connect to a cloud - object store. - """ - - BOX = 'box' - SALESFORCE = 'salesforce' - SHAREPOINT = 'sharepoint' - WEB_CRAWL = 'web_crawl' - CLOUD_OBJECT_STORAGE = 'cloud_object_storage' - - -class SourceOptions: - """ - The **options** object defines which items to crawl from the source system. - - :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 - document object types to crawl from the Salesforce source. Only valid, and - required, when the **type** field of the **source** object is set to - `salesforce`. - :param List[SourceOptionsSiteColl] site_collections: (optional) Array of - Microsoft SharePointoint Online site collections to crawl from the SharePoint - source. Only valid and required when the **type** field of the **source** object - is set to `sharepoint`. - :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 - 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. - :param bool crawl_all_buckets: (optional) When `true`, all buckets in the - specified cloud object store are crawled. If set to `true`, the **buckets** - array must not be specified. - """ - - def __init__( - self, - *, - folders: Optional[List['SourceOptionsFolder']] = None, - objects: Optional[List['SourceOptionsObject']] = None, - site_collections: Optional[List['SourceOptionsSiteColl']] = None, - urls: Optional[List['SourceOptionsWebCrawl']] = None, - buckets: Optional[List['SourceOptionsBuckets']] = None, - crawl_all_buckets: Optional[bool] = None, - ) -> None: - """ - Initialize a SourceOptions object. - - :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 - document object types to crawl from the Salesforce source. Only valid, and - required, when the **type** field of the **source** object is set to - `salesforce`. - :param List[SourceOptionsSiteColl] site_collections: (optional) Array of - Microsoft SharePointoint Online site collections to crawl from the - SharePoint source. Only valid and required when the **type** field of the - **source** object is set to `sharepoint`. - :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 - 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. - :param bool crawl_all_buckets: (optional) When `true`, all buckets in the - specified cloud object store are crawled. If set to `true`, the **buckets** - array must not be specified. - """ - self.folders = folders - self.objects = objects - self.site_collections = site_collections - self.urls = urls - self.buckets = buckets - self.crawl_all_buckets = crawl_all_buckets - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptions': - """Initialize a SourceOptions object from a json dictionary.""" - args = {} - if (folders := _dict.get('folders')) is not None: - args['folders'] = [ - SourceOptionsFolder.from_dict(v) for v in folders - ] - if (objects := _dict.get('objects')) is not None: - args['objects'] = [ - SourceOptionsObject.from_dict(v) for v in objects - ] - if (site_collections := _dict.get('site_collections')) is not None: - args['site_collections'] = [ - SourceOptionsSiteColl.from_dict(v) for v in site_collections - ] - if (urls := _dict.get('urls')) is not None: - args['urls'] = [SourceOptionsWebCrawl.from_dict(v) for v in urls] - if (buckets := _dict.get('buckets')) is not None: - args['buckets'] = [ - SourceOptionsBuckets.from_dict(v) for v in buckets - ] - if (crawl_all_buckets := _dict.get('crawl_all_buckets')) is not None: - args['crawl_all_buckets'] = crawl_all_buckets - return cls(**args) - - @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: - folders_list = [] - for v in self.folders: - if isinstance(v, dict): - folders_list.append(v) - else: - folders_list.append(v.to_dict()) - _dict['folders'] = folders_list - if hasattr(self, 'objects') and self.objects is not None: - objects_list = [] - for v in self.objects: - if isinstance(v, dict): - objects_list.append(v) - else: - objects_list.append(v.to_dict()) - _dict['objects'] = objects_list - if hasattr(self, - 'site_collections') and self.site_collections is not None: - site_collections_list = [] - for v in self.site_collections: - if isinstance(v, dict): - site_collections_list.append(v) - else: - site_collections_list.append(v.to_dict()) - _dict['site_collections'] = site_collections_list - if hasattr(self, 'urls') and self.urls is not None: - urls_list = [] - for v in self.urls: - if isinstance(v, dict): - urls_list.append(v) - else: - urls_list.append(v.to_dict()) - _dict['urls'] = urls_list - if hasattr(self, 'buckets') and self.buckets is not None: - buckets_list = [] - for v in self.buckets: - if isinstance(v, dict): - buckets_list.append(v) - else: - buckets_list.append(v.to_dict()) - _dict['buckets'] = buckets_list - if hasattr(self, - 'crawl_all_buckets') and self.crawl_all_buckets is not None: - _dict['crawl_all_buckets'] = self.crawl_all_buckets - 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 SourceOptions object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SourceOptions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsBuckets: - """ - Object defining a cloud object store bucket to crawl. - - :param str name: The name of the cloud object store bucket to crawl. - :param int limit: (optional) The number of documents to crawl from this cloud - object store bucket. If not specified, all documents in the bucket are crawled. - """ - - def __init__( - self, - name: str, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a SourceOptionsBuckets object. - - :param str name: The name of the cloud object store bucket to crawl. - :param int limit: (optional) The number of documents to crawl from this - cloud object store bucket. If not specified, all documents in the bucket - are crawled. - """ - self.name = name - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsBuckets': - """Initialize a SourceOptionsBuckets object from a json dictionary.""" - args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - else: - raise ValueError( - 'Required property \'name\' not present in SourceOptionsBuckets JSON' - ) - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @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: - _dict['name'] = self.name - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 SourceOptionsBuckets object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SourceOptionsBuckets') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsFolder: - """ - Object that defines a box folder to crawl with this configuration. - - :param str owner_user_id: The Box user ID of the user who owns the folder to - crawl. - :param str folder_id: The Box folder ID of the folder to crawl. - :param int limit: (optional) The maximum number of documents to crawl for this - folder. By default, all documents in the folder are crawled. - """ - - def __init__( - self, - owner_user_id: str, - folder_id: str, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a SourceOptionsFolder object. - - :param str owner_user_id: The Box user ID of the user who owns the folder - to crawl. - :param str folder_id: The Box folder ID of the folder to crawl. - :param int limit: (optional) The maximum number of documents to crawl for - this folder. By default, all documents in the folder are crawled. - """ - self.owner_user_id = owner_user_id - self.folder_id = folder_id - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsFolder': - """Initialize a SourceOptionsFolder object from a json dictionary.""" - args = {} - if (owner_user_id := _dict.get('owner_user_id')) is not None: - args['owner_user_id'] = owner_user_id - else: - raise ValueError( - 'Required property \'owner_user_id\' not present in SourceOptionsFolder JSON' - ) - if (folder_id := _dict.get('folder_id')) is not None: - args['folder_id'] = folder_id - else: - raise ValueError( - 'Required property \'folder_id\' not present in SourceOptionsFolder JSON' - ) - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @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: - _dict['owner_user_id'] = self.owner_user_id - if hasattr(self, 'folder_id') and self.folder_id is not None: - _dict['folder_id'] = self.folder_id - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 SourceOptionsFolder object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SourceOptionsFolder') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsObject: - """ - Object that defines a Salesforce document object type crawl with this configuration. - - :param str name: The name of the Salesforce document object to crawl. For - example, `case`. - :param int limit: (optional) The maximum number of documents to crawl for this - document object. By default, all documents in the document object are crawled. - """ - - def __init__( - self, - name: str, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a SourceOptionsObject object. - - :param str name: The name of the Salesforce document object to crawl. For - example, `case`. - :param int limit: (optional) The maximum number of documents to crawl for - this document object. By default, all documents in the document object are - crawled. - """ - self.name = name - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsObject': - """Initialize a SourceOptionsObject object from a json dictionary.""" - args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - else: - raise ValueError( - 'Required property \'name\' not present in SourceOptionsObject JSON' - ) - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @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: - _dict['name'] = self.name - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 SourceOptionsObject object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SourceOptionsObject') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsSiteColl: - """ - Object that defines a Microsoft SharePoint site collection to crawl with this - configuration. - - :param str site_collection_path: The Microsoft SharePoint Online site collection - path to crawl. The path must be be relative to the **organization_url** that was - specified in the credentials associated with this source configuration. - :param int limit: (optional) The maximum number of documents to crawl for this - site collection. By default, all documents in the site collection are crawled. - """ - - def __init__( - self, - site_collection_path: str, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a SourceOptionsSiteColl object. - - :param str site_collection_path: The Microsoft SharePoint Online site - collection path to crawl. The path must be be relative to the - **organization_url** that was specified in the credentials associated with - this source configuration. - :param int limit: (optional) The maximum number of documents to crawl for - this site collection. By default, all documents in the site collection are - crawled. - """ - self.site_collection_path = site_collection_path - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsSiteColl': - """Initialize a SourceOptionsSiteColl object from a json dictionary.""" - args = {} - if (site_collection_path := - _dict.get('site_collection_path')) is not None: - args['site_collection_path'] = site_collection_path - else: - raise ValueError( - 'Required property \'site_collection_path\' not present in SourceOptionsSiteColl JSON' - ) - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @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' - ) and self.site_collection_path is not None: - _dict['site_collection_path'] = self.site_collection_path - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 SourceOptionsSiteColl object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SourceOptionsSiteColl') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsWebCrawl: - """ - Object defining which URL to crawl and how to crawl it. - - :param str url: The starting URL to crawl. - :param bool limit_to_starting_hosts: (optional) When `true`, crawls of the - specified URL are limited to the host part of the **url** field. - :param str crawl_speed: (optional) The number of concurrent URLs to fetch. - `gentle` means one URL is fetched at a time with a delay between each call. - `normal` means as many as two URLs are fectched concurrently with a short delay - between fetch calls. `aggressive` means that up to ten URLs are fetched - concurrently with a short delay between fetch calls. - :param bool allow_untrusted_certificate: (optional) When `true`, allows the - crawl to interact with HTTPS sites with SSL certificates with untrusted signers. - :param int maximum_hops: (optional) The maximum number of hops to make from the - initial URL. When a page is crawled each link on that page will also be crawled - if it is within the **maximum_hops** from the initial URL. The first page - crawled is 0 hops, each link crawled from the first page is 1 hop, each link - crawled from those pages is 2 hops, and so on. - :param int request_timeout: (optional) The maximum milliseconds to wait for a - response from the web server. - :param bool override_robots_txt: (optional) When `true`, the crawler will ignore - any `robots.txt` encountered by the crawler. This should only ever be done when - crawling a web site the user owns. This must be be set to `true` when a - **gateway_id** is specied in the **credentials**. - :param List[str] blacklist: (optional) Array of URL's to be excluded while - crawling. The crawler will not follow links which contains this string. For - example, listing `https://ibm.com/watson` also excludes - `https://ibm.com/watson/discovery`. - """ - - def __init__( - self, - url: str, - *, - limit_to_starting_hosts: Optional[bool] = None, - crawl_speed: Optional[str] = None, - allow_untrusted_certificate: Optional[bool] = None, - maximum_hops: Optional[int] = None, - request_timeout: Optional[int] = None, - override_robots_txt: Optional[bool] = None, - blacklist: Optional[List[str]] = None, - ) -> None: - """ - Initialize a SourceOptionsWebCrawl object. - - :param str url: The starting URL to crawl. - :param bool limit_to_starting_hosts: (optional) When `true`, crawls of the - specified URL are limited to the host part of the **url** field. - :param str crawl_speed: (optional) The number of concurrent URLs to fetch. - `gentle` means one URL is fetched at a time with a delay between each call. - `normal` means as many as two URLs are fectched concurrently with a short - delay between fetch calls. `aggressive` means that up to ten URLs are - fetched concurrently with a short delay between fetch calls. - :param bool allow_untrusted_certificate: (optional) When `true`, allows the - crawl to interact with HTTPS sites with SSL certificates with untrusted - signers. - :param int maximum_hops: (optional) The maximum number of hops to make from - the initial URL. When a page is crawled each link on that page will also be - crawled if it is within the **maximum_hops** from the initial URL. The - first page crawled is 0 hops, each link crawled from the first page is 1 - hop, each link crawled from those pages is 2 hops, and so on. - :param int request_timeout: (optional) The maximum milliseconds to wait for - a response from the web server. - :param bool override_robots_txt: (optional) When `true`, the crawler will - ignore any `robots.txt` encountered by the crawler. This should only ever - be done when crawling a web site the user owns. This must be be set to - `true` when a **gateway_id** is specied in the **credentials**. - :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`. - """ - self.url = url - self.limit_to_starting_hosts = limit_to_starting_hosts - self.crawl_speed = crawl_speed - self.allow_untrusted_certificate = allow_untrusted_certificate - self.maximum_hops = maximum_hops - self.request_timeout = request_timeout - self.override_robots_txt = override_robots_txt - self.blacklist = blacklist - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsWebCrawl': - """Initialize a SourceOptionsWebCrawl object from a json dictionary.""" - args = {} - if (url := _dict.get('url')) is not None: - args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in SourceOptionsWebCrawl JSON' - ) - if (limit_to_starting_hosts := - _dict.get('limit_to_starting_hosts')) is not None: - args['limit_to_starting_hosts'] = limit_to_starting_hosts - if (crawl_speed := _dict.get('crawl_speed')) is not None: - args['crawl_speed'] = crawl_speed - if (allow_untrusted_certificate := - _dict.get('allow_untrusted_certificate')) is not None: - args['allow_untrusted_certificate'] = allow_untrusted_certificate - if (maximum_hops := _dict.get('maximum_hops')) is not None: - args['maximum_hops'] = maximum_hops - if (request_timeout := _dict.get('request_timeout')) is not None: - args['request_timeout'] = request_timeout - if (override_robots_txt := - _dict.get('override_robots_txt')) is not None: - args['override_robots_txt'] = override_robots_txt - if (blacklist := _dict.get('blacklist')) is not None: - args['blacklist'] = blacklist - return cls(**args) - - @classmethod - 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: - _dict['url'] = self.url - if hasattr(self, 'limit_to_starting_hosts' - ) and self.limit_to_starting_hosts is not None: - _dict['limit_to_starting_hosts'] = self.limit_to_starting_hosts - if hasattr(self, 'crawl_speed') and self.crawl_speed is not None: - _dict['crawl_speed'] = self.crawl_speed - if hasattr(self, 'allow_untrusted_certificate' - ) and self.allow_untrusted_certificate is not None: - _dict[ - 'allow_untrusted_certificate'] = self.allow_untrusted_certificate - if hasattr(self, 'maximum_hops') and self.maximum_hops is not None: - _dict['maximum_hops'] = self.maximum_hops - if hasattr(self, - 'request_timeout') and self.request_timeout is not None: - _dict['request_timeout'] = self.request_timeout - if hasattr( - self, - 'override_robots_txt') and self.override_robots_txt is not None: - _dict['override_robots_txt'] = self.override_robots_txt - if hasattr(self, 'blacklist') and self.blacklist is not None: - _dict['blacklist'] = self.blacklist - 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 SourceOptionsWebCrawl object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SourceOptionsWebCrawl') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class CrawlSpeedEnum(str, Enum): - """ - The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a - time with a delay between each call. `normal` means as many as two URLs are - fectched concurrently with a short delay between fetch calls. `aggressive` means - that up to ten URLs are fetched concurrently with a short delay between fetch - calls. - """ - - GENTLE = 'gentle' - NORMAL = 'normal' - AGGRESSIVE = 'aggressive' - - -class SourceSchedule: - """ - Object containing the schedule information for the source. - - :param bool enabled: (optional) When `true`, the source is re-crawled based on - the **frequency** field in this object. When `false` the source is not - re-crawled; When `false` and connecting to Salesforce the source is crawled - annually. - :param str time_zone: (optional) The time zone to base source crawl times on. - Possible values correspond to the IANA (Internet Assigned Numbers Authority) - time zones list. - :param str frequency: (optional) The crawl schedule in the specified - **time_zone**. - - `five_minutes`: Runs every five minutes. - - `hourly`: Runs every hour. - - `daily`: Runs every day between 00:00 and 06:00. - - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - - `monthly`: Runs the on the first Sunday of every month between 00:00 and - 06:00. - """ - - def __init__( - self, - *, - enabled: Optional[bool] = None, - time_zone: Optional[str] = None, - frequency: Optional[str] = None, - ) -> None: - """ - Initialize a SourceSchedule object. - - :param bool enabled: (optional) When `true`, the source is re-crawled based - on the **frequency** field in this object. When `false` the source is not - re-crawled; When `false` and connecting to Salesforce the source is crawled - annually. - :param str time_zone: (optional) The time zone to base source crawl times - on. Possible values correspond to the IANA (Internet Assigned Numbers - Authority) time zones list. - :param str frequency: (optional) The crawl schedule in the specified - **time_zone**. - - `five_minutes`: Runs every five minutes. - - `hourly`: Runs every hour. - - `daily`: Runs every day between 00:00 and 06:00. - - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - - `monthly`: Runs the on the first Sunday of every month between 00:00 and - 06:00. - """ - self.enabled = enabled - self.time_zone = time_zone - self.frequency = frequency - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceSchedule': - """Initialize a SourceSchedule object from a json dictionary.""" - args = {} - if (enabled := _dict.get('enabled')) is not None: - args['enabled'] = enabled - if (time_zone := _dict.get('time_zone')) is not None: - args['time_zone'] = time_zone - if (frequency := _dict.get('frequency')) is not None: - args['frequency'] = frequency - return cls(**args) - - @classmethod - 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: - _dict['enabled'] = self.enabled - if hasattr(self, 'time_zone') and self.time_zone is not None: - _dict['time_zone'] = self.time_zone - if hasattr(self, 'frequency') and self.frequency is not None: - _dict['frequency'] = self.frequency - 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 SourceSchedule object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SourceSchedule') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class FrequencyEnum(str, Enum): - """ - The crawl schedule in the specified **time_zone**. - - `five_minutes`: Runs every five minutes. - - `hourly`: Runs every hour. - - `daily`: Runs every day between 00:00 and 06:00. - - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - - `monthly`: Runs the on the first Sunday of every month between 00:00 and 06:00. - """ - - DAILY = 'daily' - WEEKLY = 'weekly' - MONTHLY = 'monthly' - FIVE_MINUTES = 'five_minutes' - HOURLY = 'hourly' - - -class SourceStatus: - """ - Object containing source crawl status information. - - :param str status: (optional) The current status of the source crawl for this - collection. This field returns `not_configured` if the default configuration for - this source does not have a **source** object defined. - - `running` indicates that a crawl to fetch more documents is in progress. - - `complete` indicates that the crawl has completed with no errors. - - `queued` indicates that the crawl has been paused by the system and will - automatically restart when possible. - - `unknown` indicates that an unidentified error has occured in the service. - :param datetime next_crawl: (optional) Date in `RFC 3339` format indicating the - time of the next crawl attempt. - """ - - def __init__( - self, - *, - status: Optional[str] = None, - next_crawl: Optional[datetime] = None, - ) -> None: - """ - Initialize a SourceStatus object. - - :param str status: (optional) The current status of the source crawl for - this collection. This field returns `not_configured` if the default - configuration for this source does not have a **source** object defined. - - `running` indicates that a crawl to fetch more documents is in progress. - - `complete` indicates that the crawl has completed with no errors. - - `queued` indicates that the crawl has been paused by the system and will - automatically restart when possible. - - `unknown` indicates that an unidentified error has occured in the - service. - :param datetime next_crawl: (optional) Date in `RFC 3339` format indicating - the time of the next crawl attempt. - """ - self.status = status - self.next_crawl = next_crawl - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceStatus': - """Initialize a SourceStatus object from a json dictionary.""" - args = {} - if (status := _dict.get('status')) is not None: - args['status'] = status - if (next_crawl := _dict.get('next_crawl')) is not None: - args['next_crawl'] = string_to_datetime(next_crawl) - return cls(**args) - - @classmethod - 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: - _dict['status'] = self.status - if hasattr(self, 'next_crawl') and self.next_crawl is not None: - _dict['next_crawl'] = datetime_to_string(self.next_crawl) - 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 SourceStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'SourceStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The current status of the source crawl for this collection. This field returns - `not_configured` if the default configuration for this source does not have a - **source** object defined. - - `running` indicates that a crawl to fetch more documents is in progress. - - `complete` indicates that the crawl has completed with no errors. - - `queued` indicates that the crawl has been paused by the system and will - automatically restart when possible. - - `unknown` indicates that an unidentified error has occured in the service. - """ - - RUNNING = 'running' - COMPLETE = 'complete' - NOT_CONFIGURED = 'not_configured' - QUEUED = 'queued' - UNKNOWN = 'unknown' - - -class StatusDetails: - """ - Object that contains details about the status of the authentication process. - - :param bool authenticated: (optional) Indicates whether the credential is - accepted by the target data source. - :param str error_message: (optional) If `authenticated` is `false`, a message - describes why authentication is unsuccessful. - """ - - def __init__( - self, - *, - authenticated: Optional[bool] = None, - error_message: Optional[str] = None, - ) -> None: - """ - Initialize a StatusDetails object. - - :param bool authenticated: (optional) Indicates whether the credential is - accepted by the target data source. - :param str error_message: (optional) If `authenticated` is `false`, a - message describes why authentication is unsuccessful. - """ - self.authenticated = authenticated - self.error_message = error_message - - @classmethod - def from_dict(cls, _dict: Dict) -> 'StatusDetails': - """Initialize a StatusDetails object from a json dictionary.""" - args = {} - if (authenticated := _dict.get('authenticated')) is not None: - args['authenticated'] = authenticated - if (error_message := _dict.get('error_message')) is not None: - args['error_message'] = error_message - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a StatusDetails object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'authenticated') and self.authenticated is not None: - _dict['authenticated'] = self.authenticated - if hasattr(self, 'error_message') and self.error_message is not None: - _dict['error_message'] = self.error_message - 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 StatusDetails object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'StatusDetails') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'StatusDetails') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TokenDictRule: - """ - An object defining a single tokenizaion rule. - - :param str text: The string to tokenize. - :param List[str] tokens: Array of tokens that the `text` field is split into - when found. - :param List[str] readings: (optional) Array of tokens that represent the content - of the `text` field in an alternate character set. - :param str part_of_speech: The part of speech that the `text` string belongs to. - For example `noun`. Custom parts of speech can be specified. - """ - - def __init__( - self, - text: str, - tokens: List[str], - part_of_speech: str, - *, - readings: Optional[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 - 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 - content of the `text` field in an alternate character set. - """ - self.text = text - self.tokens = tokens - self.readings = readings - self.part_of_speech = part_of_speech - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TokenDictRule': - """Initialize a TokenDictRule object from a json dictionary.""" - args = {} - if (text := _dict.get('text')) is not None: - args['text'] = text - else: - raise ValueError( - 'Required property \'text\' not present in TokenDictRule JSON') - if (tokens := _dict.get('tokens')) is not None: - args['tokens'] = tokens - else: - raise ValueError( - 'Required property \'tokens\' not present in TokenDictRule JSON' - ) - if (readings := _dict.get('readings')) is not None: - args['readings'] = readings - if (part_of_speech := _dict.get('part_of_speech')) is not None: - args['part_of_speech'] = part_of_speech - else: - raise ValueError( - 'Required property \'part_of_speech\' not present in TokenDictRule JSON' - ) - return cls(**args) - - @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: - _dict['text'] = self.text - if hasattr(self, 'tokens') and self.tokens is not None: - _dict['tokens'] = self.tokens - if hasattr(self, 'readings') and self.readings is not None: - _dict['readings'] = self.readings - if hasattr(self, 'part_of_speech') and self.part_of_speech is not None: - _dict['part_of_speech'] = self.part_of_speech - 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 TokenDictRule object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'TokenDictRule') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TokenDictStatusResponse: - """ - Object describing the current status of the wordlist. - - :param str status: (optional) Current wordlist status for the specified - collection. - :param str type: (optional) The type for this wordlist. Can be - `tokenization_dictionary` or `stopwords`. - """ - - def __init__( - self, - *, - status: Optional[str] = None, - type: Optional[str] = None, - ) -> None: - """ - Initialize a TokenDictStatusResponse object. - - :param str status: (optional) Current wordlist status for the specified - collection. - :param str type: (optional) The type for this wordlist. Can be - `tokenization_dictionary` or `stopwords`. - """ - self.status = status - self.type = type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TokenDictStatusResponse': - """Initialize a TokenDictStatusResponse object from a json dictionary.""" - args = {} - if (status := _dict.get('status')) is not None: - args['status'] = status - if (type := _dict.get('type')) is not None: - args['type'] = type - return cls(**args) - - @classmethod - 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: - _dict['status'] = self.status - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - 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 TokenDictStatusResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'TokenDictStatusResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Current wordlist status for the specified collection. - """ - - ACTIVE = 'active' - PENDING = 'pending' - NOT_FOUND = 'not found' - - -class TrainingDataSet: - """ - Training information for a specific collection. - - :param str environment_id: (optional) The environment id associated with 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. At - least 50 queries are required for training to begin. A maximum of 10,000 queries - are returned. - """ - - def __init__( - self, - *, - environment_id: Optional[str] = None, - collection_id: Optional[str] = None, - queries: Optional[List['TrainingQuery']] = None, - ) -> None: - """ - Initialize a TrainingDataSet object. - - :param str environment_id: (optional) The environment id associated with - 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. - At least 50 queries are required for training to begin. A maximum of 10,000 - queries are returned. - """ - self.environment_id = environment_id - self.collection_id = collection_id - self.queries = queries - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingDataSet': - """Initialize a TrainingDataSet object from a json dictionary.""" - args = {} - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - if (queries := _dict.get('queries')) is not None: - args['queries'] = [TrainingQuery.from_dict(v) for v in queries] - return cls(**args) - - @classmethod - 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: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'queries') and self.queries is not None: - queries_list = [] - for v in self.queries: - if isinstance(v, dict): - queries_list.append(v) - else: - queries_list.append(v.to_dict()) - _dict['queries'] = queries_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TrainingDataSet object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'TrainingDataSet') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingExample: - """ - Training example details. - - :param str document_id: (optional) The document ID associated with this training - example. - :param str cross_reference: (optional) The cross reference associated with this - training example. - :param int relevance: (optional) The relevance of the training example. - """ - - def __init__( - self, - *, - document_id: Optional[str] = None, - cross_reference: Optional[str] = None, - relevance: Optional[int] = None, - ) -> None: - """ - Initialize a TrainingExample object. - - :param str document_id: (optional) The document ID associated with this - training example. - :param str cross_reference: (optional) The cross reference associated with - this training example. - :param int relevance: (optional) The relevance of the training example. - """ - self.document_id = document_id - self.cross_reference = cross_reference - self.relevance = relevance - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingExample': - """Initialize a TrainingExample object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (cross_reference := _dict.get('cross_reference')) is not None: - args['cross_reference'] = cross_reference - if (relevance := _dict.get('relevance')) is not None: - args['relevance'] = relevance - return cls(**args) - - @classmethod - 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: - _dict['document_id'] = self.document_id - if hasattr(self, - 'cross_reference') and self.cross_reference is not None: - _dict['cross_reference'] = self.cross_reference - if hasattr(self, 'relevance') and self.relevance is not None: - _dict['relevance'] = self.relevance - 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 TrainingExample object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'TrainingExample') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingExampleList: - """ - Object containing an array of training examples. - - :param List[TrainingExample] examples: (optional) Array of training examples. - """ - - def __init__( - self, - *, - examples: Optional[List['TrainingExample']] = None, - ) -> None: - """ - Initialize a TrainingExampleList object. - - :param List[TrainingExample] examples: (optional) Array of training - examples. - """ - self.examples = examples - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingExampleList': - """Initialize a TrainingExampleList object from a json dictionary.""" - args = {} - if (examples := _dict.get('examples')) is not None: - args['examples'] = [TrainingExample.from_dict(v) for v in examples] - return cls(**args) - - @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: - examples_list = [] - for v in self.examples: - if isinstance(v, dict): - examples_list.append(v) - else: - examples_list.append(v.to_dict()) - _dict['examples'] = examples_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TrainingExampleList object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'TrainingExampleList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingQuery: - """ - Training query details. - - :param str query_id: (optional) The query ID associated with the training query. - :param str natural_language_query: (optional) The natural text query for the - training query. - :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 examples. - """ - - def __init__( - self, - *, - query_id: Optional[str] = None, - natural_language_query: Optional[str] = None, - filter: Optional[str] = None, - examples: Optional[List['TrainingExample']] = None, - ) -> None: - """ - Initialize a TrainingQuery object. - - :param str query_id: (optional) The query ID associated with the training - query. - :param str natural_language_query: (optional) The natural text query for - the training query. - :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 - examples. - """ - self.query_id = query_id - self.natural_language_query = natural_language_query - self.filter = filter - self.examples = examples - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingQuery': - """Initialize a TrainingQuery object from a json dictionary.""" - args = {} - if (query_id := _dict.get('query_id')) is not None: - args['query_id'] = query_id - if (natural_language_query := - _dict.get('natural_language_query')) is not None: - args['natural_language_query'] = natural_language_query - if (filter := _dict.get('filter')) is not None: - args['filter'] = filter - if (examples := _dict.get('examples')) is not None: - args['examples'] = [TrainingExample.from_dict(v) for v in examples] - return cls(**args) - - @classmethod - 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: - _dict['query_id'] = self.query_id - if hasattr(self, 'natural_language_query' - ) and self.natural_language_query is not None: - _dict['natural_language_query'] = self.natural_language_query - if hasattr(self, 'filter') and self.filter is not None: - _dict['filter'] = self.filter - if hasattr(self, 'examples') and self.examples is not None: - examples_list = [] - for v in self.examples: - if isinstance(v, dict): - examples_list.append(v) - else: - examples_list.append(v.to_dict()) - _dict['examples'] = examples_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TrainingQuery object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'TrainingQuery') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingStatus: - """ - Training status details. - - :param int total_examples: (optional) The total number of training examples - uploaded to this collection. - :param bool available: (optional) When `true`, the collection has been - successfully trained. - :param bool processing: (optional) When `true`, the collection is currently - processing training. - :param bool minimum_queries_added: (optional) When `true`, the collection has a - sufficent amount of queries added for training to occur. - :param bool minimum_examples_added: (optional) When `true`, the collection has a - sufficent amount of examples added for training to occur. - :param bool sufficient_label_diversity: (optional) When `true`, the collection - has a sufficent amount of diversity in labeled results for training to occur. - :param int notices: (optional) The number of notices associated with this data - set. - :param datetime successfully_trained: (optional) The timestamp of when the - collection was successfully trained. - :param datetime data_updated: (optional) The timestamp of when the data was - uploaded. - """ - - def __init__( - self, - *, - total_examples: Optional[int] = None, - available: Optional[bool] = None, - processing: Optional[bool] = None, - minimum_queries_added: Optional[bool] = None, - minimum_examples_added: Optional[bool] = None, - sufficient_label_diversity: Optional[bool] = None, - notices: Optional[int] = None, - successfully_trained: Optional[datetime] = None, - data_updated: Optional[datetime] = None, - ) -> None: - """ - Initialize a TrainingStatus object. - - :param int total_examples: (optional) The total number of training examples - uploaded to this collection. - :param bool available: (optional) When `true`, the collection has been - successfully trained. - :param bool processing: (optional) When `true`, the collection is currently - processing training. - :param bool minimum_queries_added: (optional) When `true`, the collection - has a sufficent amount of queries added for training to occur. - :param bool minimum_examples_added: (optional) When `true`, the collection - has a sufficent amount of examples added for training to occur. - :param bool sufficient_label_diversity: (optional) When `true`, the - collection has a sufficent amount of diversity in labeled results for - training to occur. - :param int notices: (optional) The number of notices associated with this - data set. - :param datetime successfully_trained: (optional) The timestamp of when the - collection was successfully trained. - :param datetime data_updated: (optional) The timestamp of when the data was - uploaded. - """ - self.total_examples = total_examples - self.available = available - self.processing = processing - self.minimum_queries_added = minimum_queries_added - self.minimum_examples_added = minimum_examples_added - self.sufficient_label_diversity = sufficient_label_diversity - self.notices = notices - self.successfully_trained = successfully_trained - self.data_updated = data_updated - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingStatus': - """Initialize a TrainingStatus object from a json dictionary.""" - args = {} - if (total_examples := _dict.get('total_examples')) is not None: - args['total_examples'] = total_examples - if (available := _dict.get('available')) is not None: - args['available'] = available - if (processing := _dict.get('processing')) is not None: - args['processing'] = processing - if (minimum_queries_added := - _dict.get('minimum_queries_added')) is not None: - args['minimum_queries_added'] = minimum_queries_added - if (minimum_examples_added := - _dict.get('minimum_examples_added')) is not None: - args['minimum_examples_added'] = minimum_examples_added - if (sufficient_label_diversity := - _dict.get('sufficient_label_diversity')) is not None: - args['sufficient_label_diversity'] = sufficient_label_diversity - if (notices := _dict.get('notices')) is not None: - args['notices'] = notices - if (successfully_trained := - _dict.get('successfully_trained')) is not None: - args['successfully_trained'] = string_to_datetime( - successfully_trained) - if (data_updated := _dict.get('data_updated')) is not None: - args['data_updated'] = string_to_datetime(data_updated) - return cls(**args) - - @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: - _dict['total_examples'] = self.total_examples - if hasattr(self, 'available') and self.available is not None: - _dict['available'] = self.available - if hasattr(self, 'processing') and self.processing is not None: - _dict['processing'] = self.processing - if hasattr(self, 'minimum_queries_added' - ) and self.minimum_queries_added is not None: - _dict['minimum_queries_added'] = self.minimum_queries_added - if hasattr(self, 'minimum_examples_added' - ) and self.minimum_examples_added is not None: - _dict['minimum_examples_added'] = self.minimum_examples_added - if hasattr(self, 'sufficient_label_diversity' - ) and self.sufficient_label_diversity is not None: - _dict[ - 'sufficient_label_diversity'] = self.sufficient_label_diversity - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = self.notices - if hasattr(self, 'successfully_trained' - ) and self.successfully_trained is not None: - _dict['successfully_trained'] = datetime_to_string( - self.successfully_trained) - if hasattr(self, 'data_updated') and self.data_updated is not None: - _dict['data_updated'] = datetime_to_string(self.data_updated) - 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 TrainingStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'TrainingStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class WordHeadingDetection: - """ - Object containing heading detection conversion settings for Microsoft Word documents. - - :param List[FontSetting] fonts: (optional) Array of font matching - configurations. - :param List[WordStyle] styles: (optional) Array of Microsoft Word styles to - convert. - """ - - def __init__( - self, - *, - fonts: Optional[List['FontSetting']] = None, - styles: Optional[List['WordStyle']] = None, - ) -> None: - """ - Initialize a WordHeadingDetection object. - - :param List[FontSetting] fonts: (optional) Array of font matching - configurations. - :param List[WordStyle] styles: (optional) Array of Microsoft Word styles to - convert. - """ - self.fonts = fonts - self.styles = styles - - @classmethod - def from_dict(cls, _dict: Dict) -> 'WordHeadingDetection': - """Initialize a WordHeadingDetection object from a json dictionary.""" - args = {} - if (fonts := _dict.get('fonts')) is not None: - args['fonts'] = [FontSetting.from_dict(v) for v in fonts] - if (styles := _dict.get('styles')) is not None: - args['styles'] = [WordStyle.from_dict(v) for v in styles] - return cls(**args) - - @classmethod - 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: - fonts_list = [] - for v in self.fonts: - if isinstance(v, dict): - fonts_list.append(v) - else: - fonts_list.append(v.to_dict()) - _dict['fonts'] = fonts_list - if hasattr(self, 'styles') and self.styles is not None: - styles_list = [] - for v in self.styles: - if isinstance(v, dict): - styles_list.append(v) - else: - styles_list.append(v.to_dict()) - _dict['styles'] = styles_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this WordHeadingDetection object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'WordHeadingDetection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class WordSettings: - """ - A list of Word conversion settings. - - :param WordHeadingDetection heading: (optional) Object containing heading - detection conversion settings for Microsoft Word documents. - """ - - def __init__( - self, - *, - heading: Optional['WordHeadingDetection'] = None, - ) -> None: - """ - Initialize a WordSettings object. - - :param WordHeadingDetection heading: (optional) Object containing heading - detection conversion settings for Microsoft Word documents. - """ - self.heading = heading - - @classmethod - def from_dict(cls, _dict: Dict) -> 'WordSettings': - """Initialize a WordSettings object from a json dictionary.""" - args = {} - if (heading := _dict.get('heading')) is not None: - args['heading'] = WordHeadingDetection.from_dict(heading) - return cls(**args) - - @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: - if isinstance(self.heading, dict): - _dict['heading'] = self.heading - else: - _dict['heading'] = self.heading.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 WordSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'WordSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class WordStyle: - """ - Microsoft Word styles to convert into a specified HTML head level. - - :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. - """ - - def __init__( - self, - *, - level: Optional[int] = None, - names: Optional[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. - """ - self.level = level - self.names = names - - @classmethod - def from_dict(cls, _dict: Dict) -> 'WordStyle': - """Initialize a WordStyle object from a json dictionary.""" - args = {} - if (level := _dict.get('level')) is not None: - args['level'] = level - if (names := _dict.get('names')) is not None: - args['names'] = names - return cls(**args) - - @classmethod - 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: - _dict['level'] = self.level - if hasattr(self, 'names') and self.names is not None: - _dict['names'] = self.names - 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 WordStyle object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'WordStyle') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class XPathPatterns: - """ - Object containing an array of XPaths. - - :param List[str] xpaths: (optional) An array to XPaths. - """ - - def __init__( - self, - *, - xpaths: Optional[List[str]] = None, - ) -> None: - """ - Initialize a XPathPatterns object. - - :param List[str] xpaths: (optional) An array to XPaths. - """ - self.xpaths = xpaths - - @classmethod - def from_dict(cls, _dict: Dict) -> 'XPathPatterns': - """Initialize a XPathPatterns object from a json dictionary.""" - args = {} - if (xpaths := _dict.get('xpaths')) is not None: - args['xpaths'] = xpaths - return cls(**args) - - @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 _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: '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 QueryCalculationAggregation(QueryAggregation): - """ - Returns a scalar calculation across all documents for the field specified. Possible - calculations include min, max, sum, average, and unique_count. - - :param str field: The field to perform the calculation on. - :param float value: (optional) The value of the calculation. - """ - - def __init__( - self, - type: str, - field: str, - *, - value: Optional[float] = None, - ) -> None: - """ - Initialize a QueryCalculationAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :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 = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryCalculationAggregation JSON' - ) - if (field := _dict.get('field')) is not None: - args['field'] = field - else: - raise ValueError( - 'Required property \'field\' not present in QueryCalculationAggregation JSON' - ) - if (value := _dict.get('value')) is not None: - args['value'] = 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 narrows the document set of the sub-aggregations it precedes. - - :param str match: The filter that is written in Discovery Query Language syntax - and is applied to the documents before sub-aggregations are run. - :param int matching_results: Number of documents that match the filter. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__( - self, - type: str, - match: str, - matching_results: int, - *, - aggregations: Optional[List['QueryAggregation']] = None, - ) -> None: - """ - Initialize a QueryFilterAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str match: The filter that is written in Discovery Query Language - syntax and is applied to the documents before sub-aggregations are run. - :param int matching_results: Number of documents that match 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 = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryFilterAggregation JSON' - ) - if (match := _dict.get('match')) is not None: - args['match'] = match - else: - raise ValueError( - 'Required property \'match\' not present in QueryFilterAggregation JSON' - ) - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' - ) - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in 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: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this 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. - - :param str field: The numeric field name used to create the histogram. - :param int interval: The size of the sections that the results are split into. - :param str name: (optional) Identifier specified in the query request of this - aggregation. - :param List[QueryHistogramAggregationResult] results: (optional) Array of - numeric intervals. - """ - - def __init__( - self, - type: str, - field: str, - interval: int, - *, - name: Optional[str] = None, - results: Optional[List['QueryHistogramAggregationResult']] = None, - ) -> None: - """ - Initialize a QueryHistogramAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str field: The numeric field name used to create the histogram. - :param int interval: The size of the sections that the results are split - into. - :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryHistogramAggregationResult] results: (optional) Array of - numeric intervals. - """ - self.type = type - self.field = field - self.interval = interval - self.name = name - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': - """Initialize a QueryHistogramAggregation object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryHistogramAggregation JSON' - ) - if (field := _dict.get('field')) is not None: - args['field'] = field - else: - raise ValueError( - 'Required property \'field\' not present in QueryHistogramAggregation JSON' - ) - if (interval := _dict.get('interval')) is not None: - args['interval'] = interval - else: - raise ValueError( - 'Required property \'interval\' not present in QueryHistogramAggregation JSON' - ) - if (name := _dict.get('name')) is not None: - args['name'] = name - if (results := _dict.get('results')) is not None: - args['results'] = [ - QueryHistogramAggregationResult.from_dict(v) for v in 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this 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 alters the document set that is used for sub-aggregations it - precedes to nested documents found in the field specified. - - :param str path: The path to the document field to scope sub-aggregations to. - :param int matching_results: Number of nested documents found in the specified - field. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__( - self, - type: str, - path: str, - matching_results: int, - *, - aggregations: Optional[List['QueryAggregation']] = None, - ) -> None: - """ - Initialize a QueryNestedAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :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 = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryNestedAggregation JSON' - ) - if (path := _dict.get('path')) is not None: - args['path'] = path - else: - raise ValueError( - 'Required property \'path\' not present in QueryNestedAggregation JSON' - ) - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' - ) - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in 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: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this 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. - - :param str field: The field in the document used to generate top values from. - :param int count: (optional) The number of top values returned. - :param str name: (optional) Identifier specified in the query request of this - aggregation. - :param List[QueryTermAggregationResult] results: (optional) Array of top values - for the field. - """ - - def __init__( - self, - type: str, - field: str, - *, - count: Optional[int] = None, - name: Optional[str] = None, - results: Optional[List['QueryTermAggregationResult']] = None, - ) -> None: - """ - Initialize a QueryTermAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str field: The field in the document used to generate top values - from. - :param int count: (optional) The number of top values returned. - :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryTermAggregationResult] results: (optional) Array of top - values for the field. - """ - self.type = type - self.field = field - self.count = count - self.name = name - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': - """Initialize a QueryTermAggregation object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryTermAggregation JSON' - ) - if (field := _dict.get('field')) is not None: - args['field'] = field - else: - raise ValueError( - 'Required property \'field\' not present in QueryTermAggregation JSON' - ) - if (count := _dict.get('count')) is not None: - args['count'] = count - if (name := _dict.get('name')) is not None: - args['name'] = name - if (results := _dict.get('results')) is not None: - args['results'] = [ - QueryTermAggregationResult.from_dict(v) for v in 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this 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. - - :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 str name: (optional) Identifier specified in the query request of this - aggregation. - :param List[QueryTimesliceAggregationResult] results: (optional) Array of - aggregation results. - """ - - def __init__( - self, - type: str, - field: str, - interval: str, - *, - name: Optional[str] = None, - results: Optional[List['QueryTimesliceAggregationResult']] = None, - ) -> None: - """ - Initialize a QueryTimesliceAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :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 str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryTimesliceAggregationResult] results: (optional) Array of - aggregation results. - """ - self.type = type - self.field = field - self.interval = interval - self.name = name - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryTimesliceAggregation JSON' - ) - if (field := _dict.get('field')) is not None: - args['field'] = field - else: - raise ValueError( - 'Required property \'field\' not present in QueryTimesliceAggregation JSON' - ) - if (interval := _dict.get('interval')) is not None: - args['interval'] = interval - else: - raise ValueError( - 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' - ) - if (name := _dict.get('name')) is not None: - args['name'] = name - if (results := _dict.get('results')) is not None: - args['results'] = [ - QueryTimesliceAggregationResult.from_dict(v) for v in 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this 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. - - :param int size: The number of documents to return. - :param str name: (optional) Identifier specified in the query request of this - aggregation. - :param QueryTopHitsAggregationResult hits: (optional) - """ - - def __init__( - self, - type: str, - size: int, - *, - name: Optional[str] = None, - hits: Optional['QueryTopHitsAggregationResult'] = None, - ) -> None: - """ - Initialize a QueryTopHitsAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param int size: The number of documents to return. - :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param QueryTopHitsAggregationResult hits: (optional) - """ - self.type = type - self.size = size - self.name = name - self.hits = hits - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryTopHitsAggregation JSON' - ) - if (size := _dict.get('size')) is not None: - args['size'] = size - else: - raise ValueError( - 'Required property \'size\' not present in QueryTopHitsAggregation JSON' - ) - if (name := _dict.get('name')) is not None: - args['name'] = name - if (hits := _dict.get('hits')) is not None: - args['hits'] = QueryTopHitsAggregationResult.from_dict(hits) - return cls(**args) - - @classmethod - 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'hits') and self.hits is not None: - if isinstance(self.hits, dict): - _dict['hits'] = self.hits - else: - _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: 'QueryTopHitsAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other diff --git a/test/integration/test_discovery_v1.py b/test/integration/test_discovery_v1.py deleted file mode 100644 index 6809fefe..00000000 --- a/test/integration/test_discovery_v1.py +++ /dev/null @@ -1,292 +0,0 @@ -# coding: utf-8 -from unittest import TestCase -import os -import ibm_watson -import random -import pytest - - -@pytest.mark.skipif(os.getenv('DISCOVERY_APIKEY') is None, - reason='requires DISCOVERY_APIKEY') -class Discoveryv1(TestCase): - discovery = None - environment_id = os.getenv('DISCOVERY_ENVIRONMENT_ID') # This environment is created for integration testing - collection_id = None - collection_name = 'FOR-PYTHON-DELETE-ME' - - @classmethod - def setup_class(cls): - cls.discovery = ibm_watson.DiscoveryV1(version='2018-08-01') - cls.discovery.set_default_headers({ - 'X-Watson-Learning-Opt-Out': '1', - 'X-Watson-Test': '1' - }) - - collections = cls.discovery.list_collections( - cls.environment_id).get_result()['collections'] - for collection in collections: - if collection['name'] == cls.collection_name: - cls.collection_id = collection['collection_id'] - - if cls.collection_id is None: - print("Creating a new temporary collection") - cls.collection_id = cls.discovery.create_collection( - cls.environment_id, - cls.collection_name, - description="Integration test for python sdk").get_result( - )['collection_id'] - - @classmethod - def teardown_class(cls): - collections = cls.discovery.list_collections( - cls.environment_id).get_result()['collections'] - for collection in collections: - if collection['name'] == cls.collection_name: - print('Deleting the temporary collection') - cls.discovery.delete_collection(cls.environment_id, - cls.collection_id) - break - - def test_environments(self): - envs = self.discovery.list_environments().get_result() - assert envs is not None - env = self.discovery.get_environment( - envs['environments'][0]['environment_id']).get_result() - assert env is not None - fields = self.discovery.list_fields(self.environment_id, - self.collection_id).get_result() - assert fields is not None - - def test_configurations(self): - configs = self.discovery.list_configurations( - self.environment_id).get_result() - assert configs is not None - - name = 'test' + random.choice('ABCDEFGHIJKLMNOPQ') - new_configuration_id = self.discovery.create_configuration( - self.environment_id, - name, - description='creating new config for python sdk').get_result( - )['configuration_id'] - assert new_configuration_id is not None - self.discovery.get_configuration(self.environment_id, - new_configuration_id).get_result() - - updated_config = self.discovery.update_configuration( - self.environment_id, new_configuration_id, 'lala').get_result() - assert updated_config['name'] == 'lala' - - deleted_config = self.discovery.delete_configuration( - self.environment_id, new_configuration_id).get_result() - assert deleted_config['status'] == 'deleted' - - def test_collections_and_expansions(self): - self.discovery.get_collection(self.environment_id, self.collection_id) - updated_collection = self.discovery.update_collection( - self.environment_id, - self.collection_id, - self.collection_name, - description='Updating description').get_result() - assert updated_collection['description'] == 'Updating description' - - self.discovery.create_expansions(self.environment_id, - self.collection_id, [{ - 'input_terms': ['a'], - 'expanded_terms': ['aa'] - }]).get_result() - expansions = self.discovery.list_expansions( - self.environment_id, self.collection_id).get_result() - assert expansions['expansions'] - self.discovery.delete_expansions(self.environment_id, - self.collection_id) - - def test_documents(self): - with open( - os.path.join(os.path.dirname(__file__), - '../../resources/simple.html'), 'r') as fileinfo: - add_doc = self.discovery.add_document( - environment_id=self.environment_id, - collection_id=self.collection_id, - file=fileinfo).get_result() - assert add_doc['document_id'] is not None - - doc_status = self.discovery.get_document_status( - self.environment_id, self.collection_id, - add_doc['document_id']).get_result() - assert doc_status is not None - - with open( - os.path.join(os.path.dirname(__file__), - '../../resources/simple.html'), 'r') as fileinfo: - update_doc = self.discovery.update_document( - self.environment_id, - self.collection_id, - add_doc['document_id'], - file=fileinfo, - filename='newname.html').get_result() - assert update_doc is not None - delete_doc = self.discovery.delete_document( - self.environment_id, self.collection_id, - add_doc['document_id']).get_result() - assert delete_doc['status'] == 'deleted' - - def test_queries(self): - query_results = self.discovery.query( - self.environment_id, - self.collection_id, - filter='extracted_metadata.sha1::9181d244*').get_result() - assert query_results is not None - - @pytest.mark.skip( - reason="Temporary skipping because update_credentials fails") - def test_credentials(self): - credential_details = { - 'credential_type': 'username_password', - 'url': 'https://login.salesforce.com', - 'username': 'user@email.com', - 'password': 'xxx' - } - credentials = self.discovery.create_credentials( - self.environment_id, - source_type='salesforce', - credential_details=credential_details).get_result() - assert credentials['credential_id'] is not None - credential_id = credentials['credential_id'] - - get_credentials = self.discovery.get_credentials( - self.environment_id, credential_id).get_result() - assert get_credentials['credential_id'] == credential_id - - list_credentials = self.discovery.list_credentials( - self.environment_id).get_result() - assert list_credentials is not None - - new_credential_details = { - 'credential_type': 'username_password', - 'url': 'https://logo.salesforce.com', - 'username': 'user@email.com', - 'password': 'xxx' - } - updated_credentials = self.discovery.update_credentials( - self.environment_id, - credential_id, - source_type='salesforce', - credential_details=new_credential_details).get_result() - assert updated_credentials is not None - - get_credentials = self.discovery.get_credentials( - self.environment_id, credentials['credential_id']).get_result() - assert get_credentials['credential_details'][ - 'url'] == new_credential_details['url'] - - delete_credentials = self.discovery.delete_credentials( - self.environment_id, credential_id).get_result() - assert delete_credentials['credential_id'] is not None - - def test_create_event(self): - # create test document - with open( - os.path.join(os.path.dirname(__file__), - '../../resources/simple.html'), 'r') as fileinfo: - add_doc = self.discovery.add_document( - environment_id=self.environment_id, - collection_id=self.collection_id, - file=fileinfo).get_result() - assert add_doc['document_id'] is not None - document_id = add_doc['document_id'] - - # make query to get session token - query = self.discovery.query( - self.environment_id, - self.collection_id, - natural_language_query='The content of the first chapter' - ).get_result() - assert query['session_token'] is not None - - # create_event - event_data = { - "environment_id": self.environment_id, - "session_token": query['session_token'], - "collection_id": self.collection_id, - "document_id": document_id, - } - create_event_response = self.discovery.create_event( - 'click', event_data).get_result() - assert create_event_response['type'] == 'click' - - #delete the documment - self.discovery.delete_document(self.environment_id, self.collection_id, - document_id).get_result() - - @pytest.mark.skip(reason="Temporary disable") - def test_tokenization_dictionary(self): - result = self.discovery.get_tokenization_dictionary_status( - self.environment_id, self.collection_id).get_result() - assert result['status'] is not None - - def test_feedback(self): - response = self.discovery.get_metrics_event_rate( - start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() - assert response['aggregations'] is not None - - response = self.discovery.get_metrics_query( - start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() - assert response['aggregations'] is not None - - response = self.discovery.get_metrics_query_event( - start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() - assert response['aggregations'] is not None - - response = self.discovery.get_metrics_query_no_results( - start_time='2018-07-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document').get_result() - assert response['aggregations'] is not None - - response = self.discovery.get_metrics_query_token_event( - count=10).get_result() - assert response['aggregations'] is not None - - response = self.discovery.query_log(count=2).get_result() - assert response is not None - - @pytest.mark.skip(reason="Skip temporarily.") - def test_stopword_operations(self): - with open( - os.path.join(os.path.dirname(__file__), - '../../resources/stopwords.txt'), - 'r') as stopwords_file: - create_stopword_list_result = self.discovery.create_stopword_list( - self.environment_id, self.collection_id, - stopwords_file).get_result() - assert create_stopword_list_result is not None - - delete_stopword_list_result = self.discovery.delete_stopword_list( - self.environment_id, self.collection_id).get_result() - assert delete_stopword_list_result is None - - def test_gateway_configuration(self): - create_gateway_result = self.discovery.create_gateway( - self.environment_id, - name='test-gateway-configuration-python').get_result() - assert create_gateway_result['gateway_id'] is not None - - get_gateway_result = self.discovery.get_gateway( - self.environment_id, - create_gateway_result['gateway_id']).get_result() - assert get_gateway_result is not None - - list_gateways_result = self.discovery.list_gateways( - self.environment_id).get_result() - assert list_gateways_result is not None - - delete_gateways_result = self.discovery.delete_gateway( - self.environment_id, - create_gateway_result['gateway_id']).get_result() - assert delete_gateways_result is not None diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py deleted file mode 100644 index 0a154443..00000000 --- a/test/unit/test_discovery_v1.py +++ /dev/null @@ -1,12080 +0,0 @@ -# -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2024. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# 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. - -""" -Unit Tests for DiscoveryV1 -""" - -from datetime import datetime, timezone -from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator -from ibm_cloud_sdk_core.utils import date_to_string, string_to_date -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime -import inspect -import io -import json -import pytest -import re -import requests -import responses -import tempfile -import urllib -from ibm_watson.discovery_v1 import * - -version = 'testString' - -_service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version=version, -) - -_base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' -_service.set_service_url(_base_url) - - -def preprocess_url(operation_path: str): - """ - Returns the request url associated with the specified operation path. - This will be base_url concatenated with a quoted version of operation_path. - The returned request URL is used to register the mock response so it needs - to match the request URL that is formed by the requests library. - """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. - request_url = _base_url + operation_path - - # If the request url does NOT end with a /, then just return it as-is. - # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: - return request_url - return re.compile(request_url.rstrip('/') + '/+') - - -############################################################################## -# Start of Service: Environments -############################################################################## -# region - - -class TestCreateEnvironment: - """ - Test Class for create_environment - """ - - @responses.activate - def test_create_environment_all_params(self): - """ - create_environment() - """ - # Set up mock - url = preprocess_url('/v1/environments') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - name = 'testString' - description = 'testString' - size = 'LT' - - # Invoke method - response = _service.create_environment( - name, - description=description, - size=size, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['size'] == 'LT' - - def test_create_environment_all_params_with_retries(self): - # Enable retries and run test_create_environment_all_params. - _service.enable_retries() - self.test_create_environment_all_params() - - # Disable retries and run test_create_environment_all_params. - _service.disable_retries() - self.test_create_environment_all_params() - - @responses.activate - def test_create_environment_value_error(self): - """ - test_create_environment_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - name = 'testString' - description = 'testString' - size = 'LT' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "name": name, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_environment(**req_copy) - - def test_create_environment_value_error_with_retries(self): - # Enable retries and run test_create_environment_value_error. - _service.enable_retries() - self.test_create_environment_value_error() - - # Disable retries and run test_create_environment_value_error. - _service.disable_retries() - self.test_create_environment_value_error() - - -class TestListEnvironments: - """ - Test Class for list_environments - """ - - @responses.activate - def test_list_environments_all_params(self): - """ - list_environments() - """ - # Set up mock - url = preprocess_url('/v1/environments') - mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - name = 'testString' - - # Invoke method - response = _service.list_environments( - name=name, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'name={}'.format(name) in query_string - - def test_list_environments_all_params_with_retries(self): - # Enable retries and run test_list_environments_all_params. - _service.enable_retries() - self.test_list_environments_all_params() - - # Disable retries and run test_list_environments_all_params. - _service.disable_retries() - self.test_list_environments_all_params() - - @responses.activate - def test_list_environments_required_params(self): - """ - test_list_environments_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments') - mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.list_environments() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_environments_required_params_with_retries(self): - # Enable retries and run test_list_environments_required_params. - _service.enable_retries() - self.test_list_environments_required_params() - - # Disable retries and run test_list_environments_required_params. - _service.disable_retries() - self.test_list_environments_required_params() - - @responses.activate - def test_list_environments_value_error(self): - """ - test_list_environments_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments') - mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_environments(**req_copy) - - def test_list_environments_value_error_with_retries(self): - # Enable retries and run test_list_environments_value_error. - _service.enable_retries() - self.test_list_environments_value_error() - - # Disable retries and run test_list_environments_value_error. - _service.disable_retries() - self.test_list_environments_value_error() - - -class TestGetEnvironment: - """ - Test Class for get_environment - """ - - @responses.activate - def test_get_environment_all_params(self): - """ - get_environment() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.get_environment( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_environment_all_params_with_retries(self): - # Enable retries and run test_get_environment_all_params. - _service.enable_retries() - self.test_get_environment_all_params() - - # Disable retries and run test_get_environment_all_params. - _service.disable_retries() - self.test_get_environment_all_params() - - @responses.activate - def test_get_environment_value_error(self): - """ - test_get_environment_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_environment(**req_copy) - - def test_get_environment_value_error_with_retries(self): - # Enable retries and run test_get_environment_value_error. - _service.enable_retries() - self.test_get_environment_value_error() - - # Disable retries and run test_get_environment_value_error. - _service.disable_retries() - self.test_get_environment_value_error() - - -class TestUpdateEnvironment: - """ - Test Class for update_environment - """ - - @responses.activate - def test_update_environment_all_params(self): - """ - update_environment() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - size = 'S' - - # Invoke method - response = _service.update_environment( - environment_id, - name=name, - description=description, - size=size, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['size'] == 'S' - - def test_update_environment_all_params_with_retries(self): - # Enable retries and run test_update_environment_all_params. - _service.enable_retries() - self.test_update_environment_all_params() - - # Disable retries and run test_update_environment_all_params. - _service.disable_retries() - self.test_update_environment_all_params() - - @responses.activate - def test_update_environment_value_error(self): - """ - test_update_environment_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - size = 'S' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_environment(**req_copy) - - def test_update_environment_value_error_with_retries(self): - # Enable retries and run test_update_environment_value_error. - _service.enable_retries() - self.test_update_environment_value_error() - - # Disable retries and run test_update_environment_value_error. - _service.disable_retries() - self.test_update_environment_value_error() - - -class TestDeleteEnvironment: - """ - Test Class for delete_environment - """ - - @responses.activate - def test_delete_environment_all_params(self): - """ - delete_environment() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.delete_environment( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_environment_all_params_with_retries(self): - # Enable retries and run test_delete_environment_all_params. - _service.enable_retries() - self.test_delete_environment_all_params() - - # Disable retries and run test_delete_environment_all_params. - _service.disable_retries() - self.test_delete_environment_all_params() - - @responses.activate - def test_delete_environment_value_error(self): - """ - test_delete_environment_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_environment(**req_copy) - - def test_delete_environment_value_error_with_retries(self): - # Enable retries and run test_delete_environment_value_error. - _service.enable_retries() - self.test_delete_environment_value_error() - - # Disable retries and run test_delete_environment_value_error. - _service.disable_retries() - self.test_delete_environment_value_error() - - -class TestListFields: - """ - Test Class for list_fields - """ - - @responses.activate - def test_list_fields_all_params(self): - """ - list_fields() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = ['testString'] - - # Invoke method - response = _service.list_fields( - environment_id, - collection_ids, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string - - def test_list_fields_all_params_with_retries(self): - # Enable retries and run test_list_fields_all_params. - _service.enable_retries() - self.test_list_fields_all_params() - - # Disable retries and run test_list_fields_all_params. - _service.disable_retries() - self.test_list_fields_all_params() - - @responses.activate - def test_list_fields_value_error(self): - """ - test_list_fields_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = ['testString'] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_ids": collection_ids, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_fields(**req_copy) - - def test_list_fields_value_error_with_retries(self): - # Enable retries and run test_list_fields_value_error. - _service.enable_retries() - self.test_list_fields_value_error() - - # Disable retries and run test_list_fields_value_error. - _service.disable_retries() - self.test_list_fields_value_error() - - -# endregion -############################################################################## -# End of Service: Environments -############################################################################## - -############################################################################## -# Start of Service: Configurations -############################################################################## -# region - - -class TestCreateConfiguration: - """ - Test Class for create_configuration - """ - - @responses.activate - def test_create_configuration_all_params(self): - """ - create_configuration() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Construct a dict representation of a FontSetting model - font_setting_model = {} - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - # Construct a dict representation of a PdfHeadingDetection model - pdf_heading_detection_model = {} - pdf_heading_detection_model['fonts'] = [font_setting_model] - - # Construct a dict representation of a PdfSettings model - pdf_settings_model = {} - pdf_settings_model['heading'] = pdf_heading_detection_model - - # Construct a dict representation of a WordStyle model - word_style_model = {} - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - # Construct a dict representation of a WordHeadingDetection model - word_heading_detection_model = {} - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - # Construct a dict representation of a WordSettings model - word_settings_model = {} - word_settings_model['heading'] = word_heading_detection_model - - # Construct a dict representation of a XPathPatterns model - x_path_patterns_model = {} - x_path_patterns_model['xpaths'] = ['testString'] - - # Construct a dict representation of a HtmlSettings model - html_settings_model = {} - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - # Construct a dict representation of a SegmentSettings model - segment_settings_model = {} - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - # Construct a dict representation of a NormalizationOperation model - normalization_operation_model = {} - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - # Construct a dict representation of a Conversions model - conversions_model = {} - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - # Construct a dict representation of a NluEnrichmentKeywords model - nlu_enrichment_keywords_model = {} - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentEntities model - nlu_enrichment_entities_model = {} - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentSentiment model - nlu_enrichment_sentiment_model = {} - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentEmotion model - nlu_enrichment_emotion_model = {} - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentSemanticRoles model - nlu_enrichment_semantic_roles_model = {} - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentRelations model - nlu_enrichment_relations_model = {} - nlu_enrichment_relations_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentConcepts model - nlu_enrichment_concepts_model = {} - nlu_enrichment_concepts_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentFeatures model - nlu_enrichment_features_model = {} - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - # Construct a dict representation of a Enrichment model - enrichment_model = {} - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'testString' - enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - # Construct a dict representation of a SourceSchedule model - source_schedule_model = {} - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - # Construct a dict representation of a SourceOptionsFolder model - source_options_folder_model = {} - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsObject model - source_options_object_model = {} - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsSiteColl model - source_options_site_coll_model = {} - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsWebCrawl model - source_options_web_crawl_model = {} - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - # Construct a dict representation of a SourceOptionsBuckets model - source_options_buckets_model = {} - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - # Construct a dict representation of a SourceOptions model - source_options_model = {} - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - # Construct a dict representation of a Source model - source_model = {} - source_model['type'] = 'box' - source_model['credential_id'] = 'testString' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - conversions = conversions_model - enrichments = [enrichment_model] - normalizations = [normalization_operation_model] - source = source_model - - # Invoke method - response = _service.create_configuration( - environment_id, - name, - description=description, - conversions=conversions, - enrichments=enrichments, - normalizations=normalizations, - source=source, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['conversions'] == conversions_model - assert req_body['enrichments'] == [enrichment_model] - assert req_body['normalizations'] == [normalization_operation_model] - assert req_body['source'] == source_model - - def test_create_configuration_all_params_with_retries(self): - # Enable retries and run test_create_configuration_all_params. - _service.enable_retries() - self.test_create_configuration_all_params() - - # Disable retries and run test_create_configuration_all_params. - _service.disable_retries() - self.test_create_configuration_all_params() - - @responses.activate - def test_create_configuration_value_error(self): - """ - test_create_configuration_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Construct a dict representation of a FontSetting model - font_setting_model = {} - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - # Construct a dict representation of a PdfHeadingDetection model - pdf_heading_detection_model = {} - pdf_heading_detection_model['fonts'] = [font_setting_model] - - # Construct a dict representation of a PdfSettings model - pdf_settings_model = {} - pdf_settings_model['heading'] = pdf_heading_detection_model - - # Construct a dict representation of a WordStyle model - word_style_model = {} - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - # Construct a dict representation of a WordHeadingDetection model - word_heading_detection_model = {} - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - # Construct a dict representation of a WordSettings model - word_settings_model = {} - word_settings_model['heading'] = word_heading_detection_model - - # Construct a dict representation of a XPathPatterns model - x_path_patterns_model = {} - x_path_patterns_model['xpaths'] = ['testString'] - - # Construct a dict representation of a HtmlSettings model - html_settings_model = {} - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - # Construct a dict representation of a SegmentSettings model - segment_settings_model = {} - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - # Construct a dict representation of a NormalizationOperation model - normalization_operation_model = {} - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - # Construct a dict representation of a Conversions model - conversions_model = {} - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - # Construct a dict representation of a NluEnrichmentKeywords model - nlu_enrichment_keywords_model = {} - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentEntities model - nlu_enrichment_entities_model = {} - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentSentiment model - nlu_enrichment_sentiment_model = {} - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentEmotion model - nlu_enrichment_emotion_model = {} - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentSemanticRoles model - nlu_enrichment_semantic_roles_model = {} - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentRelations model - nlu_enrichment_relations_model = {} - nlu_enrichment_relations_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentConcepts model - nlu_enrichment_concepts_model = {} - nlu_enrichment_concepts_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentFeatures model - nlu_enrichment_features_model = {} - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - # Construct a dict representation of a Enrichment model - enrichment_model = {} - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'testString' - enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - # Construct a dict representation of a SourceSchedule model - source_schedule_model = {} - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - # Construct a dict representation of a SourceOptionsFolder model - source_options_folder_model = {} - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsObject model - source_options_object_model = {} - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsSiteColl model - source_options_site_coll_model = {} - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsWebCrawl model - source_options_web_crawl_model = {} - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - # Construct a dict representation of a SourceOptionsBuckets model - source_options_buckets_model = {} - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - # Construct a dict representation of a SourceOptions model - source_options_model = {} - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - # Construct a dict representation of a Source model - source_model = {} - source_model['type'] = 'box' - source_model['credential_id'] = 'testString' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - conversions = conversions_model - enrichments = [enrichment_model] - normalizations = [normalization_operation_model] - source = source_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "name": name, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_configuration(**req_copy) - - def test_create_configuration_value_error_with_retries(self): - # Enable retries and run test_create_configuration_value_error. - _service.enable_retries() - self.test_create_configuration_value_error() - - # Disable retries and run test_create_configuration_value_error. - _service.disable_retries() - self.test_create_configuration_value_error() - - -class TestListConfigurations: - """ - Test Class for list_configurations - """ - - @responses.activate - def test_list_configurations_all_params(self): - """ - list_configurations() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - - # Invoke method - response = _service.list_configurations( - environment_id, - name=name, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'name={}'.format(name) in query_string - - def test_list_configurations_all_params_with_retries(self): - # Enable retries and run test_list_configurations_all_params. - _service.enable_retries() - self.test_list_configurations_all_params() - - # Disable retries and run test_list_configurations_all_params. - _service.disable_retries() - self.test_list_configurations_all_params() - - @responses.activate - def test_list_configurations_required_params(self): - """ - test_list_configurations_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.list_configurations( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_configurations_required_params_with_retries(self): - # Enable retries and run test_list_configurations_required_params. - _service.enable_retries() - self.test_list_configurations_required_params() - - # Disable retries and run test_list_configurations_required_params. - _service.disable_retries() - self.test_list_configurations_required_params() - - @responses.activate - def test_list_configurations_value_error(self): - """ - test_list_configurations_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_configurations(**req_copy) - - def test_list_configurations_value_error_with_retries(self): - # Enable retries and run test_list_configurations_value_error. - _service.enable_retries() - self.test_list_configurations_value_error() - - # Disable retries and run test_list_configurations_value_error. - _service.disable_retries() - self.test_list_configurations_value_error() - - -class TestGetConfiguration: - """ - Test Class for get_configuration - """ - - @responses.activate - def test_get_configuration_all_params(self): - """ - get_configuration() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - - # Invoke method - response = _service.get_configuration( - environment_id, - configuration_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_configuration_all_params_with_retries(self): - # Enable retries and run test_get_configuration_all_params. - _service.enable_retries() - self.test_get_configuration_all_params() - - # Disable retries and run test_get_configuration_all_params. - _service.disable_retries() - self.test_get_configuration_all_params() - - @responses.activate - def test_get_configuration_value_error(self): - """ - test_get_configuration_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "configuration_id": configuration_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_configuration(**req_copy) - - def test_get_configuration_value_error_with_retries(self): - # Enable retries and run test_get_configuration_value_error. - _service.enable_retries() - self.test_get_configuration_value_error() - - # Disable retries and run test_get_configuration_value_error. - _service.disable_retries() - self.test_get_configuration_value_error() - - -class TestUpdateConfiguration: - """ - Test Class for update_configuration - """ - - @responses.activate - def test_update_configuration_all_params(self): - """ - update_configuration() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a FontSetting model - font_setting_model = {} - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - # Construct a dict representation of a PdfHeadingDetection model - pdf_heading_detection_model = {} - pdf_heading_detection_model['fonts'] = [font_setting_model] - - # Construct a dict representation of a PdfSettings model - pdf_settings_model = {} - pdf_settings_model['heading'] = pdf_heading_detection_model - - # Construct a dict representation of a WordStyle model - word_style_model = {} - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - # Construct a dict representation of a WordHeadingDetection model - word_heading_detection_model = {} - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - # Construct a dict representation of a WordSettings model - word_settings_model = {} - word_settings_model['heading'] = word_heading_detection_model - - # Construct a dict representation of a XPathPatterns model - x_path_patterns_model = {} - x_path_patterns_model['xpaths'] = ['testString'] - - # Construct a dict representation of a HtmlSettings model - html_settings_model = {} - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - # Construct a dict representation of a SegmentSettings model - segment_settings_model = {} - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - # Construct a dict representation of a NormalizationOperation model - normalization_operation_model = {} - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - # Construct a dict representation of a Conversions model - conversions_model = {} - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - # Construct a dict representation of a NluEnrichmentKeywords model - nlu_enrichment_keywords_model = {} - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentEntities model - nlu_enrichment_entities_model = {} - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentSentiment model - nlu_enrichment_sentiment_model = {} - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentEmotion model - nlu_enrichment_emotion_model = {} - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentSemanticRoles model - nlu_enrichment_semantic_roles_model = {} - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentRelations model - nlu_enrichment_relations_model = {} - nlu_enrichment_relations_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentConcepts model - nlu_enrichment_concepts_model = {} - nlu_enrichment_concepts_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentFeatures model - nlu_enrichment_features_model = {} - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - # Construct a dict representation of a Enrichment model - enrichment_model = {} - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'testString' - enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - # Construct a dict representation of a SourceSchedule model - source_schedule_model = {} - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - # Construct a dict representation of a SourceOptionsFolder model - source_options_folder_model = {} - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsObject model - source_options_object_model = {} - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsSiteColl model - source_options_site_coll_model = {} - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsWebCrawl model - source_options_web_crawl_model = {} - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - # Construct a dict representation of a SourceOptionsBuckets model - source_options_buckets_model = {} - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - # Construct a dict representation of a SourceOptions model - source_options_model = {} - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - # Construct a dict representation of a Source model - source_model = {} - source_model['type'] = 'box' - source_model['credential_id'] = 'testString' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - name = 'testString' - description = 'testString' - conversions = conversions_model - enrichments = [enrichment_model] - normalizations = [normalization_operation_model] - source = source_model - - # Invoke method - response = _service.update_configuration( - environment_id, - configuration_id, - name, - description=description, - conversions=conversions, - enrichments=enrichments, - normalizations=normalizations, - source=source, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['conversions'] == conversions_model - assert req_body['enrichments'] == [enrichment_model] - assert req_body['normalizations'] == [normalization_operation_model] - assert req_body['source'] == source_model - - def test_update_configuration_all_params_with_retries(self): - # Enable retries and run test_update_configuration_all_params. - _service.enable_retries() - self.test_update_configuration_all_params() - - # Disable retries and run test_update_configuration_all_params. - _service.disable_retries() - self.test_update_configuration_all_params() - - @responses.activate - def test_update_configuration_value_error(self): - """ - test_update_configuration_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a FontSetting model - font_setting_model = {} - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - # Construct a dict representation of a PdfHeadingDetection model - pdf_heading_detection_model = {} - pdf_heading_detection_model['fonts'] = [font_setting_model] - - # Construct a dict representation of a PdfSettings model - pdf_settings_model = {} - pdf_settings_model['heading'] = pdf_heading_detection_model - - # Construct a dict representation of a WordStyle model - word_style_model = {} - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - # Construct a dict representation of a WordHeadingDetection model - word_heading_detection_model = {} - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - # Construct a dict representation of a WordSettings model - word_settings_model = {} - word_settings_model['heading'] = word_heading_detection_model - - # Construct a dict representation of a XPathPatterns model - x_path_patterns_model = {} - x_path_patterns_model['xpaths'] = ['testString'] - - # Construct a dict representation of a HtmlSettings model - html_settings_model = {} - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - # Construct a dict representation of a SegmentSettings model - segment_settings_model = {} - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - # Construct a dict representation of a NormalizationOperation model - normalization_operation_model = {} - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - # Construct a dict representation of a Conversions model - conversions_model = {} - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - # Construct a dict representation of a NluEnrichmentKeywords model - nlu_enrichment_keywords_model = {} - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentEntities model - nlu_enrichment_entities_model = {} - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentSentiment model - nlu_enrichment_sentiment_model = {} - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentEmotion model - nlu_enrichment_emotion_model = {} - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentSemanticRoles model - nlu_enrichment_semantic_roles_model = {} - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentRelations model - nlu_enrichment_relations_model = {} - nlu_enrichment_relations_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentConcepts model - nlu_enrichment_concepts_model = {} - nlu_enrichment_concepts_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentFeatures model - nlu_enrichment_features_model = {} - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - # Construct a dict representation of a Enrichment model - enrichment_model = {} - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'testString' - enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - # Construct a dict representation of a SourceSchedule model - source_schedule_model = {} - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - # Construct a dict representation of a SourceOptionsFolder model - source_options_folder_model = {} - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsObject model - source_options_object_model = {} - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsSiteColl model - source_options_site_coll_model = {} - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsWebCrawl model - source_options_web_crawl_model = {} - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - # Construct a dict representation of a SourceOptionsBuckets model - source_options_buckets_model = {} - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - # Construct a dict representation of a SourceOptions model - source_options_model = {} - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - # Construct a dict representation of a Source model - source_model = {} - source_model['type'] = 'box' - source_model['credential_id'] = 'testString' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - name = 'testString' - description = 'testString' - conversions = conversions_model - enrichments = [enrichment_model] - normalizations = [normalization_operation_model] - source = source_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "configuration_id": configuration_id, - "name": name, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_configuration(**req_copy) - - def test_update_configuration_value_error_with_retries(self): - # Enable retries and run test_update_configuration_value_error. - _service.enable_retries() - self.test_update_configuration_value_error() - - # Disable retries and run test_update_configuration_value_error. - _service.disable_retries() - self.test_update_configuration_value_error() - - -class TestDeleteConfiguration: - """ - Test Class for delete_configuration - """ - - @responses.activate - def test_delete_configuration_all_params(self): - """ - delete_configuration() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - - # Invoke method - response = _service.delete_configuration( - environment_id, - configuration_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_configuration_all_params_with_retries(self): - # Enable retries and run test_delete_configuration_all_params. - _service.enable_retries() - self.test_delete_configuration_all_params() - - # Disable retries and run test_delete_configuration_all_params. - _service.disable_retries() - self.test_delete_configuration_all_params() - - @responses.activate - def test_delete_configuration_value_error(self): - """ - test_delete_configuration_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "configuration_id": configuration_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_configuration(**req_copy) - - def test_delete_configuration_value_error_with_retries(self): - # Enable retries and run test_delete_configuration_value_error. - _service.enable_retries() - self.test_delete_configuration_value_error() - - # Disable retries and run test_delete_configuration_value_error. - _service.disable_retries() - self.test_delete_configuration_value_error() - - -# endregion -############################################################################## -# End of Service: Configurations -############################################################################## - -############################################################################## -# Start of Service: Collections -############################################################################## -# region - - -class TestCreateCollection: - """ - Test Class for create_collection - """ - - @responses.activate - def test_create_collection_all_params(self): - """ - create_collection() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - configuration_id = 'testString' - language = 'en' - - # Invoke method - response = _service.create_collection( - environment_id, - name, - description=description, - configuration_id=configuration_id, - language=language, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['configuration_id'] == 'testString' - assert req_body['language'] == 'en' - - def test_create_collection_all_params_with_retries(self): - # Enable retries and run test_create_collection_all_params. - _service.enable_retries() - self.test_create_collection_all_params() - - # Disable retries and run test_create_collection_all_params. - _service.disable_retries() - self.test_create_collection_all_params() - - @responses.activate - def test_create_collection_value_error(self): - """ - test_create_collection_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - configuration_id = 'testString' - language = 'en' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "name": name, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_collection(**req_copy) - - def test_create_collection_value_error_with_retries(self): - # Enable retries and run test_create_collection_value_error. - _service.enable_retries() - self.test_create_collection_value_error() - - # Disable retries and run test_create_collection_value_error. - _service.disable_retries() - self.test_create_collection_value_error() - - -class TestListCollections: - """ - Test Class for list_collections - """ - - @responses.activate - def test_list_collections_all_params(self): - """ - list_collections() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - - # Invoke method - response = _service.list_collections( - environment_id, - name=name, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'name={}'.format(name) in query_string - - def test_list_collections_all_params_with_retries(self): - # Enable retries and run test_list_collections_all_params. - _service.enable_retries() - self.test_list_collections_all_params() - - # Disable retries and run test_list_collections_all_params. - _service.disable_retries() - self.test_list_collections_all_params() - - @responses.activate - def test_list_collections_required_params(self): - """ - test_list_collections_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.list_collections( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_collections_required_params_with_retries(self): - # Enable retries and run test_list_collections_required_params. - _service.enable_retries() - self.test_list_collections_required_params() - - # Disable retries and run test_list_collections_required_params. - _service.disable_retries() - self.test_list_collections_required_params() - - @responses.activate - def test_list_collections_value_error(self): - """ - test_list_collections_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_collections(**req_copy) - - def test_list_collections_value_error_with_retries(self): - # Enable retries and run test_list_collections_value_error. - _service.enable_retries() - self.test_list_collections_value_error() - - # Disable retries and run test_list_collections_value_error. - _service.disable_retries() - self.test_list_collections_value_error() - - -class TestGetCollection: - """ - Test Class for get_collection - """ - - @responses.activate - def test_get_collection_all_params(self): - """ - get_collection() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.get_collection( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_collection_all_params_with_retries(self): - # Enable retries and run test_get_collection_all_params. - _service.enable_retries() - self.test_get_collection_all_params() - - # Disable retries and run test_get_collection_all_params. - _service.disable_retries() - self.test_get_collection_all_params() - - @responses.activate - def test_get_collection_value_error(self): - """ - test_get_collection_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_collection(**req_copy) - - def test_get_collection_value_error_with_retries(self): - # Enable retries and run test_get_collection_value_error. - _service.enable_retries() - self.test_get_collection_value_error() - - # Disable retries and run test_get_collection_value_error. - _service.disable_retries() - self.test_get_collection_value_error() - - -class TestUpdateCollection: - """ - Test Class for update_collection - """ - - @responses.activate - def test_update_collection_all_params(self): - """ - update_collection() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - name = 'testString' - description = 'testString' - configuration_id = 'testString' - - # Invoke method - response = _service.update_collection( - environment_id, - collection_id, - name, - description=description, - configuration_id=configuration_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['configuration_id'] == 'testString' - - def test_update_collection_all_params_with_retries(self): - # Enable retries and run test_update_collection_all_params. - _service.enable_retries() - self.test_update_collection_all_params() - - # Disable retries and run test_update_collection_all_params. - _service.disable_retries() - self.test_update_collection_all_params() - - @responses.activate - def test_update_collection_value_error(self): - """ - test_update_collection_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - name = 'testString' - description = 'testString' - configuration_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "name": name, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_collection(**req_copy) - - def test_update_collection_value_error_with_retries(self): - # Enable retries and run test_update_collection_value_error. - _service.enable_retries() - self.test_update_collection_value_error() - - # Disable retries and run test_update_collection_value_error. - _service.disable_retries() - self.test_update_collection_value_error() - - -class TestDeleteCollection: - """ - Test Class for delete_collection - """ - - @responses.activate - def test_delete_collection_all_params(self): - """ - delete_collection() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.delete_collection( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_collection_all_params_with_retries(self): - # Enable retries and run test_delete_collection_all_params. - _service.enable_retries() - self.test_delete_collection_all_params() - - # Disable retries and run test_delete_collection_all_params. - _service.disable_retries() - self.test_delete_collection_all_params() - - @responses.activate - def test_delete_collection_value_error(self): - """ - test_delete_collection_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_collection(**req_copy) - - def test_delete_collection_value_error_with_retries(self): - # Enable retries and run test_delete_collection_value_error. - _service.enable_retries() - self.test_delete_collection_value_error() - - # Disable retries and run test_delete_collection_value_error. - _service.disable_retries() - self.test_delete_collection_value_error() - - -class TestListCollectionFields: - """ - Test Class for list_collection_fields - """ - - @responses.activate - def test_list_collection_fields_all_params(self): - """ - list_collection_fields() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.list_collection_fields( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_collection_fields_all_params_with_retries(self): - # Enable retries and run test_list_collection_fields_all_params. - _service.enable_retries() - self.test_list_collection_fields_all_params() - - # Disable retries and run test_list_collection_fields_all_params. - _service.disable_retries() - self.test_list_collection_fields_all_params() - - @responses.activate - def test_list_collection_fields_value_error(self): - """ - test_list_collection_fields_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_collection_fields(**req_copy) - - def test_list_collection_fields_value_error_with_retries(self): - # Enable retries and run test_list_collection_fields_value_error. - _service.enable_retries() - self.test_list_collection_fields_value_error() - - # Disable retries and run test_list_collection_fields_value_error. - _service.disable_retries() - self.test_list_collection_fields_value_error() - - -# endregion -############################################################################## -# End of Service: Collections -############################################################################## - -############################################################################## -# Start of Service: QueryModifications -############################################################################## -# region - - -class TestListExpansions: - """ - Test Class for list_expansions - """ - - @responses.activate - def test_list_expansions_all_params(self): - """ - list_expansions() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.list_expansions( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_expansions_all_params_with_retries(self): - # Enable retries and run test_list_expansions_all_params. - _service.enable_retries() - self.test_list_expansions_all_params() - - # Disable retries and run test_list_expansions_all_params. - _service.disable_retries() - self.test_list_expansions_all_params() - - @responses.activate - def test_list_expansions_value_error(self): - """ - test_list_expansions_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_expansions(**req_copy) - - def test_list_expansions_value_error_with_retries(self): - # Enable retries and run test_list_expansions_value_error. - _service.enable_retries() - self.test_list_expansions_value_error() - - # Disable retries and run test_list_expansions_value_error. - _service.disable_retries() - self.test_list_expansions_value_error() - - -class TestCreateExpansions: - """ - Test Class for create_expansions - """ - - @responses.activate - def test_create_expansions_all_params(self): - """ - create_expansions() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a Expansion model - expansion_model = {} - expansion_model['input_terms'] = ['testString'] - expansion_model['expanded_terms'] = ['testString'] - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - expansions = [expansion_model] - - # Invoke method - response = _service.create_expansions( - environment_id, - collection_id, - expansions, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['expansions'] == [expansion_model] - - def test_create_expansions_all_params_with_retries(self): - # Enable retries and run test_create_expansions_all_params. - _service.enable_retries() - self.test_create_expansions_all_params() - - # Disable retries and run test_create_expansions_all_params. - _service.disable_retries() - self.test_create_expansions_all_params() - - @responses.activate - def test_create_expansions_value_error(self): - """ - test_create_expansions_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a Expansion model - expansion_model = {} - expansion_model['input_terms'] = ['testString'] - expansion_model['expanded_terms'] = ['testString'] - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - expansions = [expansion_model] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "expansions": expansions, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_expansions(**req_copy) - - def test_create_expansions_value_error_with_retries(self): - # Enable retries and run test_create_expansions_value_error. - _service.enable_retries() - self.test_create_expansions_value_error() - - # Disable retries and run test_create_expansions_value_error. - _service.disable_retries() - self.test_create_expansions_value_error() - - -class TestDeleteExpansions: - """ - Test Class for delete_expansions - """ - - @responses.activate - def test_delete_expansions_all_params(self): - """ - delete_expansions() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.delete_expansions( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 204 - - def test_delete_expansions_all_params_with_retries(self): - # Enable retries and run test_delete_expansions_all_params. - _service.enable_retries() - self.test_delete_expansions_all_params() - - # Disable retries and run test_delete_expansions_all_params. - _service.disable_retries() - self.test_delete_expansions_all_params() - - @responses.activate - def test_delete_expansions_value_error(self): - """ - test_delete_expansions_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_expansions(**req_copy) - - def test_delete_expansions_value_error_with_retries(self): - # Enable retries and run test_delete_expansions_value_error. - _service.enable_retries() - self.test_delete_expansions_value_error() - - # Disable retries and run test_delete_expansions_value_error. - _service.disable_retries() - self.test_delete_expansions_value_error() - - -class TestGetTokenizationDictionaryStatus: - """ - Test Class for get_tokenization_dictionary_status - """ - - @responses.activate - def test_get_tokenization_dictionary_status_all_params(self): - """ - get_tokenization_dictionary_status() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.get_tokenization_dictionary_status( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_tokenization_dictionary_status_all_params_with_retries(self): - # Enable retries and run test_get_tokenization_dictionary_status_all_params. - _service.enable_retries() - self.test_get_tokenization_dictionary_status_all_params() - - # Disable retries and run test_get_tokenization_dictionary_status_all_params. - _service.disable_retries() - self.test_get_tokenization_dictionary_status_all_params() - - @responses.activate - def test_get_tokenization_dictionary_status_value_error(self): - """ - test_get_tokenization_dictionary_status_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_tokenization_dictionary_status(**req_copy) - - def test_get_tokenization_dictionary_status_value_error_with_retries(self): - # Enable retries and run test_get_tokenization_dictionary_status_value_error. - _service.enable_retries() - self.test_get_tokenization_dictionary_status_value_error() - - # Disable retries and run test_get_tokenization_dictionary_status_value_error. - _service.disable_retries() - self.test_get_tokenization_dictionary_status_value_error() - - -class TestCreateTokenizationDictionary: - """ - Test Class for create_tokenization_dictionary - """ - - @responses.activate - def test_create_tokenization_dictionary_all_params(self): - """ - create_tokenization_dictionary() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Construct a dict representation of a TokenDictRule model - token_dict_rule_model = {} - token_dict_rule_model['text'] = 'testString' - token_dict_rule_model['tokens'] = ['testString'] - token_dict_rule_model['readings'] = ['testString'] - token_dict_rule_model['part_of_speech'] = 'testString' - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - tokenization_rules = [token_dict_rule_model] - - # Invoke method - response = _service.create_tokenization_dictionary( - environment_id, - collection_id, - tokenization_rules=tokenization_rules, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['tokenization_rules'] == [token_dict_rule_model] - - def test_create_tokenization_dictionary_all_params_with_retries(self): - # Enable retries and run test_create_tokenization_dictionary_all_params. - _service.enable_retries() - self.test_create_tokenization_dictionary_all_params() - - # Disable retries and run test_create_tokenization_dictionary_all_params. - _service.disable_retries() - self.test_create_tokenization_dictionary_all_params() - - @responses.activate - def test_create_tokenization_dictionary_required_params(self): - """ - test_create_tokenization_dictionary_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.create_tokenization_dictionary( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_create_tokenization_dictionary_required_params_with_retries(self): - # Enable retries and run test_create_tokenization_dictionary_required_params. - _service.enable_retries() - self.test_create_tokenization_dictionary_required_params() - - # Disable retries and run test_create_tokenization_dictionary_required_params. - _service.disable_retries() - self.test_create_tokenization_dictionary_required_params() - - @responses.activate - def test_create_tokenization_dictionary_value_error(self): - """ - test_create_tokenization_dictionary_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_tokenization_dictionary(**req_copy) - - def test_create_tokenization_dictionary_value_error_with_retries(self): - # Enable retries and run test_create_tokenization_dictionary_value_error. - _service.enable_retries() - self.test_create_tokenization_dictionary_value_error() - - # Disable retries and run test_create_tokenization_dictionary_value_error. - _service.disable_retries() - self.test_create_tokenization_dictionary_value_error() - - -class TestDeleteTokenizationDictionary: - """ - Test Class for delete_tokenization_dictionary - """ - - @responses.activate - def test_delete_tokenization_dictionary_all_params(self): - """ - delete_tokenization_dictionary() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.delete_tokenization_dictionary( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_tokenization_dictionary_all_params_with_retries(self): - # Enable retries and run test_delete_tokenization_dictionary_all_params. - _service.enable_retries() - self.test_delete_tokenization_dictionary_all_params() - - # Disable retries and run test_delete_tokenization_dictionary_all_params. - _service.disable_retries() - self.test_delete_tokenization_dictionary_all_params() - - @responses.activate - def test_delete_tokenization_dictionary_value_error(self): - """ - test_delete_tokenization_dictionary_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_tokenization_dictionary(**req_copy) - - def test_delete_tokenization_dictionary_value_error_with_retries(self): - # Enable retries and run test_delete_tokenization_dictionary_value_error. - _service.enable_retries() - self.test_delete_tokenization_dictionary_value_error() - - # Disable retries and run test_delete_tokenization_dictionary_value_error. - _service.disable_retries() - self.test_delete_tokenization_dictionary_value_error() - - -class TestGetStopwordListStatus: - """ - Test Class for get_stopword_list_status - """ - - @responses.activate - def test_get_stopword_list_status_all_params(self): - """ - get_stopword_list_status() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.get_stopword_list_status( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_stopword_list_status_all_params_with_retries(self): - # Enable retries and run test_get_stopword_list_status_all_params. - _service.enable_retries() - self.test_get_stopword_list_status_all_params() - - # Disable retries and run test_get_stopword_list_status_all_params. - _service.disable_retries() - self.test_get_stopword_list_status_all_params() - - @responses.activate - def test_get_stopword_list_status_value_error(self): - """ - test_get_stopword_list_status_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_stopword_list_status(**req_copy) - - def test_get_stopword_list_status_value_error_with_retries(self): - # Enable retries and run test_get_stopword_list_status_value_error. - _service.enable_retries() - self.test_get_stopword_list_status_value_error() - - # Disable retries and run test_get_stopword_list_status_value_error. - _service.disable_retries() - self.test_get_stopword_list_status_value_error() - - -class TestCreateStopwordList: - """ - Test Class for create_stopword_list - """ - - @responses.activate - def test_create_stopword_list_all_params(self): - """ - create_stopword_list() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - stopword_file = io.BytesIO(b'This is a mock file.').getvalue() - stopword_filename = 'testString' - - # Invoke method - response = _service.create_stopword_list( - environment_id, - collection_id, - stopword_file, - stopword_filename=stopword_filename, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_create_stopword_list_all_params_with_retries(self): - # Enable retries and run test_create_stopword_list_all_params. - _service.enable_retries() - self.test_create_stopword_list_all_params() - - # Disable retries and run test_create_stopword_list_all_params. - _service.disable_retries() - self.test_create_stopword_list_all_params() - - @responses.activate - def test_create_stopword_list_required_params(self): - """ - test_create_stopword_list_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - stopword_file = io.BytesIO(b'This is a mock file.').getvalue() - stopword_filename = 'testString' - - # Invoke method - response = _service.create_stopword_list( - environment_id, - collection_id, - stopword_file, - stopword_filename=stopword_filename, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_create_stopword_list_required_params_with_retries(self): - # Enable retries and run test_create_stopword_list_required_params. - _service.enable_retries() - self.test_create_stopword_list_required_params() - - # Disable retries and run test_create_stopword_list_required_params. - _service.disable_retries() - self.test_create_stopword_list_required_params() - - @responses.activate - def test_create_stopword_list_value_error(self): - """ - test_create_stopword_list_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - stopword_file = io.BytesIO(b'This is a mock file.').getvalue() - stopword_filename = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "stopword_file": stopword_file, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_stopword_list(**req_copy) - - def test_create_stopword_list_value_error_with_retries(self): - # Enable retries and run test_create_stopword_list_value_error. - _service.enable_retries() - self.test_create_stopword_list_value_error() - - # Disable retries and run test_create_stopword_list_value_error. - _service.disable_retries() - self.test_create_stopword_list_value_error() - - -class TestDeleteStopwordList: - """ - Test Class for delete_stopword_list - """ - - @responses.activate - def test_delete_stopword_list_all_params(self): - """ - delete_stopword_list() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.delete_stopword_list( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_stopword_list_all_params_with_retries(self): - # Enable retries and run test_delete_stopword_list_all_params. - _service.enable_retries() - self.test_delete_stopword_list_all_params() - - # Disable retries and run test_delete_stopword_list_all_params. - _service.disable_retries() - self.test_delete_stopword_list_all_params() - - @responses.activate - def test_delete_stopword_list_value_error(self): - """ - test_delete_stopword_list_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_stopword_list(**req_copy) - - def test_delete_stopword_list_value_error_with_retries(self): - # Enable retries and run test_delete_stopword_list_value_error. - _service.enable_retries() - self.test_delete_stopword_list_value_error() - - # Disable retries and run test_delete_stopword_list_value_error. - _service.disable_retries() - self.test_delete_stopword_list_value_error() - - -# endregion -############################################################################## -# End of Service: QueryModifications -############################################################################## - -############################################################################## -# Start of Service: Documents -############################################################################## -# region - - -class TestAddDocument: - """ - Test Class for add_document - """ - - @responses.activate - def test_add_document_all_params(self): - """ - add_document() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/json' - metadata = 'testString' - - # Invoke method - response = _service.add_document( - environment_id, - collection_id, - file=file, - filename=filename, - file_content_type=file_content_type, - metadata=metadata, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_add_document_all_params_with_retries(self): - # Enable retries and run test_add_document_all_params. - _service.enable_retries() - self.test_add_document_all_params() - - # Disable retries and run test_add_document_all_params. - _service.disable_retries() - self.test_add_document_all_params() - - @responses.activate - def test_add_document_required_params(self): - """ - test_add_document_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.add_document( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_add_document_required_params_with_retries(self): - # Enable retries and run test_add_document_required_params. - _service.enable_retries() - self.test_add_document_required_params() - - # Disable retries and run test_add_document_required_params. - _service.disable_retries() - self.test_add_document_required_params() - - @responses.activate - def test_add_document_value_error(self): - """ - test_add_document_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.add_document(**req_copy) - - def test_add_document_value_error_with_retries(self): - # Enable retries and run test_add_document_value_error. - _service.enable_retries() - self.test_add_document_value_error() - - # Disable retries and run test_add_document_value_error. - _service.disable_retries() - self.test_add_document_value_error() - - -class TestGetDocumentStatus: - """ - Test Class for get_document_status - """ - - @responses.activate - def test_get_document_status_all_params(self): - """ - get_document_status() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Invoke method - response = _service.get_document_status( - environment_id, - collection_id, - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_document_status_all_params_with_retries(self): - # Enable retries and run test_get_document_status_all_params. - _service.enable_retries() - self.test_get_document_status_all_params() - - # Disable retries and run test_get_document_status_all_params. - _service.disable_retries() - self.test_get_document_status_all_params() - - @responses.activate - def test_get_document_status_value_error(self): - """ - test_get_document_status_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_document_status(**req_copy) - - def test_get_document_status_value_error_with_retries(self): - # Enable retries and run test_get_document_status_value_error. - _service.enable_retries() - self.test_get_document_status_value_error() - - # Disable retries and run test_get_document_status_value_error. - _service.disable_retries() - self.test_get_document_status_value_error() - - -class TestUpdateDocument: - """ - Test Class for update_document - """ - - @responses.activate - def test_update_document_all_params(self): - """ - update_document() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/json' - metadata = 'testString' - - # Invoke method - response = _service.update_document( - environment_id, - collection_id, - document_id, - file=file, - filename=filename, - file_content_type=file_content_type, - metadata=metadata, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_update_document_all_params_with_retries(self): - # Enable retries and run test_update_document_all_params. - _service.enable_retries() - self.test_update_document_all_params() - - # Disable retries and run test_update_document_all_params. - _service.disable_retries() - self.test_update_document_all_params() - - @responses.activate - def test_update_document_required_params(self): - """ - test_update_document_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Invoke method - response = _service.update_document( - environment_id, - collection_id, - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_update_document_required_params_with_retries(self): - # Enable retries and run test_update_document_required_params. - _service.enable_retries() - self.test_update_document_required_params() - - # Disable retries and run test_update_document_required_params. - _service.disable_retries() - self.test_update_document_required_params() - - @responses.activate - def test_update_document_value_error(self): - """ - test_update_document_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_document(**req_copy) - - def test_update_document_value_error_with_retries(self): - # Enable retries and run test_update_document_value_error. - _service.enable_retries() - self.test_update_document_value_error() - - # Disable retries and run test_update_document_value_error. - _service.disable_retries() - self.test_update_document_value_error() - - -class TestDeleteDocument: - """ - Test Class for delete_document - """ - - @responses.activate - def test_delete_document_all_params(self): - """ - delete_document() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Invoke method - response = _service.delete_document( - environment_id, - collection_id, - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_document_all_params_with_retries(self): - # Enable retries and run test_delete_document_all_params. - _service.enable_retries() - self.test_delete_document_all_params() - - # Disable retries and run test_delete_document_all_params. - _service.disable_retries() - self.test_delete_document_all_params() - - @responses.activate - def test_delete_document_value_error(self): - """ - test_delete_document_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_document(**req_copy) - - def test_delete_document_value_error_with_retries(self): - # Enable retries and run test_delete_document_value_error. - _service.enable_retries() - self.test_delete_document_value_error() - - # Disable retries and run test_delete_document_value_error. - _service.disable_retries() - self.test_delete_document_value_error() - - -# endregion -############################################################################## -# End of Service: Documents -############################################################################## - -############################################################################## -# Start of Service: Queries -############################################################################## -# region - - -class TestQuery: - """ - Test Class for query - """ - - @responses.activate - def test_query_all_params(self): - """ - query() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - passages = True - aggregation = 'testString' - count = 10 - return_ = 'testString' - offset = 38 - sort = 'testString' - highlight = False - passages_fields = 'testString' - passages_count = 10 - passages_characters = 400 - deduplicate = False - deduplicate_field = 'testString' - similar = False - similar_document_ids = 'testString' - similar_fields = 'testString' - bias = 'testString' - spelling_suggestions = False - x_watson_logging_opt_out = False - - # Invoke method - response = _service.query( - environment_id, - collection_id, - filter=filter, - query=query, - natural_language_query=natural_language_query, - passages=passages, - aggregation=aggregation, - count=count, - return_=return_, - offset=offset, - sort=sort, - highlight=highlight, - passages_fields=passages_fields, - passages_count=passages_count, - passages_characters=passages_characters, - deduplicate=deduplicate, - deduplicate_field=deduplicate_field, - similar=similar, - similar_document_ids=similar_document_ids, - similar_fields=similar_fields, - bias=bias, - spelling_suggestions=spelling_suggestions, - x_watson_logging_opt_out=x_watson_logging_opt_out, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['filter'] == 'testString' - assert req_body['query'] == 'testString' - assert req_body['natural_language_query'] == 'testString' - assert req_body['passages'] == True - assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 10 - assert req_body['return'] == 'testString' - assert req_body['offset'] == 38 - assert req_body['sort'] == 'testString' - assert req_body['highlight'] == False - assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 10 - assert req_body['passages.characters'] == 400 - assert req_body['deduplicate'] == False - assert req_body['deduplicate.field'] == 'testString' - assert req_body['similar'] == False - assert req_body['similar.document_ids'] == 'testString' - assert req_body['similar.fields'] == 'testString' - assert req_body['bias'] == 'testString' - assert req_body['spelling_suggestions'] == False - - def test_query_all_params_with_retries(self): - # Enable retries and run test_query_all_params. - _service.enable_retries() - self.test_query_all_params() - - # Disable retries and run test_query_all_params. - _service.disable_retries() - self.test_query_all_params() - - @responses.activate - def test_query_required_params(self): - """ - test_query_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.query( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_query_required_params_with_retries(self): - # Enable retries and run test_query_required_params. - _service.enable_retries() - self.test_query_required_params() - - # Disable retries and run test_query_required_params. - _service.disable_retries() - self.test_query_required_params() - - @responses.activate - def test_query_value_error(self): - """ - test_query_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.query(**req_copy) - - def test_query_value_error_with_retries(self): - # Enable retries and run test_query_value_error. - _service.enable_retries() - self.test_query_value_error() - - # Disable retries and run test_query_value_error. - _service.disable_retries() - self.test_query_value_error() - - -class TestQueryNotices: - """ - Test Class for query_notices - """ - - @responses.activate - def test_query_notices_all_params(self): - """ - query_notices() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - passages = True - aggregation = 'testString' - count = 10 - return_ = ['testString'] - offset = 38 - sort = ['testString'] - highlight = False - passages_fields = ['testString'] - passages_count = 10 - passages_characters = 400 - deduplicate_field = 'testString' - similar = False - similar_document_ids = ['testString'] - similar_fields = ['testString'] - - # Invoke method - response = _service.query_notices( - environment_id, - collection_id, - filter=filter, - query=query, - natural_language_query=natural_language_query, - passages=passages, - aggregation=aggregation, - count=count, - return_=return_, - offset=offset, - sort=sort, - highlight=highlight, - passages_fields=passages_fields, - passages_count=passages_count, - passages_characters=passages_characters, - deduplicate_field=deduplicate_field, - similar=similar, - similar_document_ids=similar_document_ids, - similar_fields=similar_fields, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'filter={}'.format(filter) in query_string - assert 'query={}'.format(query) in query_string - assert 'natural_language_query={}'.format(natural_language_query) in query_string - assert 'passages={}'.format('true' if passages else 'false') in query_string - assert 'aggregation={}'.format(aggregation) in query_string - assert 'count={}'.format(count) in query_string - assert 'return={}'.format(','.join(return_)) in query_string - assert 'offset={}'.format(offset) in query_string - assert 'sort={}'.format(','.join(sort)) in query_string - assert 'highlight={}'.format('true' if highlight else 'false') in query_string - assert 'passages.fields={}'.format(','.join(passages_fields)) in query_string - assert 'passages.count={}'.format(passages_count) in query_string - assert 'passages.characters={}'.format(passages_characters) in query_string - assert 'deduplicate.field={}'.format(deduplicate_field) in query_string - assert 'similar={}'.format('true' if similar else 'false') in query_string - assert 'similar.document_ids={}'.format(','.join(similar_document_ids)) in query_string - assert 'similar.fields={}'.format(','.join(similar_fields)) in query_string - - def test_query_notices_all_params_with_retries(self): - # Enable retries and run test_query_notices_all_params. - _service.enable_retries() - self.test_query_notices_all_params() - - # Disable retries and run test_query_notices_all_params. - _service.disable_retries() - self.test_query_notices_all_params() - - @responses.activate - def test_query_notices_required_params(self): - """ - test_query_notices_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.query_notices( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_query_notices_required_params_with_retries(self): - # Enable retries and run test_query_notices_required_params. - _service.enable_retries() - self.test_query_notices_required_params() - - # Disable retries and run test_query_notices_required_params. - _service.disable_retries() - self.test_query_notices_required_params() - - @responses.activate - def test_query_notices_value_error(self): - """ - test_query_notices_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.query_notices(**req_copy) - - def test_query_notices_value_error_with_retries(self): - # Enable retries and run test_query_notices_value_error. - _service.enable_retries() - self.test_query_notices_value_error() - - # Disable retries and run test_query_notices_value_error. - _service.disable_retries() - self.test_query_notices_value_error() - - -class TestFederatedQuery: - """ - Test Class for federated_query - """ - - @responses.activate - def test_federated_query_all_params(self): - """ - federated_query() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = 'testString' - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - passages = True - aggregation = 'testString' - count = 10 - return_ = 'testString' - offset = 38 - sort = 'testString' - highlight = False - passages_fields = 'testString' - passages_count = 10 - passages_characters = 400 - deduplicate = False - deduplicate_field = 'testString' - similar = False - similar_document_ids = 'testString' - similar_fields = 'testString' - bias = 'testString' - x_watson_logging_opt_out = False - - # Invoke method - response = _service.federated_query( - environment_id, - collection_ids, - filter=filter, - query=query, - natural_language_query=natural_language_query, - passages=passages, - aggregation=aggregation, - count=count, - return_=return_, - offset=offset, - sort=sort, - highlight=highlight, - passages_fields=passages_fields, - passages_count=passages_count, - passages_characters=passages_characters, - deduplicate=deduplicate, - deduplicate_field=deduplicate_field, - similar=similar, - similar_document_ids=similar_document_ids, - similar_fields=similar_fields, - bias=bias, - x_watson_logging_opt_out=x_watson_logging_opt_out, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['collection_ids'] == 'testString' - assert req_body['filter'] == 'testString' - assert req_body['query'] == 'testString' - assert req_body['natural_language_query'] == 'testString' - assert req_body['passages'] == True - assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 10 - assert req_body['return'] == 'testString' - assert req_body['offset'] == 38 - assert req_body['sort'] == 'testString' - assert req_body['highlight'] == False - assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 10 - assert req_body['passages.characters'] == 400 - assert req_body['deduplicate'] == False - assert req_body['deduplicate.field'] == 'testString' - assert req_body['similar'] == False - assert req_body['similar.document_ids'] == 'testString' - assert req_body['similar.fields'] == 'testString' - assert req_body['bias'] == 'testString' - - def test_federated_query_all_params_with_retries(self): - # Enable retries and run test_federated_query_all_params. - _service.enable_retries() - self.test_federated_query_all_params() - - # Disable retries and run test_federated_query_all_params. - _service.disable_retries() - self.test_federated_query_all_params() - - @responses.activate - def test_federated_query_required_params(self): - """ - test_federated_query_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = 'testString' - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - passages = True - aggregation = 'testString' - count = 10 - return_ = 'testString' - offset = 38 - sort = 'testString' - highlight = False - passages_fields = 'testString' - passages_count = 10 - passages_characters = 400 - deduplicate = False - deduplicate_field = 'testString' - similar = False - similar_document_ids = 'testString' - similar_fields = 'testString' - bias = 'testString' - - # Invoke method - response = _service.federated_query( - environment_id, - collection_ids, - filter=filter, - query=query, - natural_language_query=natural_language_query, - passages=passages, - aggregation=aggregation, - count=count, - return_=return_, - offset=offset, - sort=sort, - highlight=highlight, - passages_fields=passages_fields, - passages_count=passages_count, - passages_characters=passages_characters, - deduplicate=deduplicate, - deduplicate_field=deduplicate_field, - similar=similar, - similar_document_ids=similar_document_ids, - similar_fields=similar_fields, - bias=bias, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['collection_ids'] == 'testString' - assert req_body['filter'] == 'testString' - assert req_body['query'] == 'testString' - assert req_body['natural_language_query'] == 'testString' - assert req_body['passages'] == True - assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 10 - assert req_body['return'] == 'testString' - assert req_body['offset'] == 38 - assert req_body['sort'] == 'testString' - assert req_body['highlight'] == False - assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 10 - assert req_body['passages.characters'] == 400 - assert req_body['deduplicate'] == False - assert req_body['deduplicate.field'] == 'testString' - assert req_body['similar'] == False - assert req_body['similar.document_ids'] == 'testString' - assert req_body['similar.fields'] == 'testString' - assert req_body['bias'] == 'testString' - - def test_federated_query_required_params_with_retries(self): - # Enable retries and run test_federated_query_required_params. - _service.enable_retries() - self.test_federated_query_required_params() - - # Disable retries and run test_federated_query_required_params. - _service.disable_retries() - self.test_federated_query_required_params() - - @responses.activate - def test_federated_query_value_error(self): - """ - test_federated_query_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = 'testString' - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - passages = True - aggregation = 'testString' - count = 10 - return_ = 'testString' - offset = 38 - sort = 'testString' - highlight = False - passages_fields = 'testString' - passages_count = 10 - passages_characters = 400 - deduplicate = False - deduplicate_field = 'testString' - similar = False - similar_document_ids = 'testString' - similar_fields = 'testString' - bias = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_ids": collection_ids, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.federated_query(**req_copy) - - def test_federated_query_value_error_with_retries(self): - # Enable retries and run test_federated_query_value_error. - _service.enable_retries() - self.test_federated_query_value_error() - - # Disable retries and run test_federated_query_value_error. - _service.disable_retries() - self.test_federated_query_value_error() - - -class TestFederatedQueryNotices: - """ - Test Class for federated_query_notices - """ - - @responses.activate - def test_federated_query_notices_all_params(self): - """ - federated_query_notices() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = ['testString'] - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - aggregation = 'testString' - count = 10 - return_ = ['testString'] - offset = 38 - sort = ['testString'] - highlight = False - deduplicate_field = 'testString' - similar = False - similar_document_ids = ['testString'] - similar_fields = ['testString'] - - # Invoke method - response = _service.federated_query_notices( - environment_id, - collection_ids, - filter=filter, - query=query, - natural_language_query=natural_language_query, - aggregation=aggregation, - count=count, - return_=return_, - offset=offset, - sort=sort, - highlight=highlight, - deduplicate_field=deduplicate_field, - similar=similar, - similar_document_ids=similar_document_ids, - similar_fields=similar_fields, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string - assert 'filter={}'.format(filter) in query_string - assert 'query={}'.format(query) in query_string - assert 'natural_language_query={}'.format(natural_language_query) in query_string - assert 'aggregation={}'.format(aggregation) in query_string - assert 'count={}'.format(count) in query_string - assert 'return={}'.format(','.join(return_)) in query_string - assert 'offset={}'.format(offset) in query_string - assert 'sort={}'.format(','.join(sort)) in query_string - assert 'highlight={}'.format('true' if highlight else 'false') in query_string - assert 'deduplicate.field={}'.format(deduplicate_field) in query_string - assert 'similar={}'.format('true' if similar else 'false') in query_string - assert 'similar.document_ids={}'.format(','.join(similar_document_ids)) in query_string - assert 'similar.fields={}'.format(','.join(similar_fields)) in query_string - - def test_federated_query_notices_all_params_with_retries(self): - # Enable retries and run test_federated_query_notices_all_params. - _service.enable_retries() - self.test_federated_query_notices_all_params() - - # Disable retries and run test_federated_query_notices_all_params. - _service.disable_retries() - self.test_federated_query_notices_all_params() - - @responses.activate - def test_federated_query_notices_required_params(self): - """ - test_federated_query_notices_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = ['testString'] - - # Invoke method - response = _service.federated_query_notices( - environment_id, - collection_ids, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string - - def test_federated_query_notices_required_params_with_retries(self): - # Enable retries and run test_federated_query_notices_required_params. - _service.enable_retries() - self.test_federated_query_notices_required_params() - - # Disable retries and run test_federated_query_notices_required_params. - _service.disable_retries() - self.test_federated_query_notices_required_params() - - @responses.activate - def test_federated_query_notices_value_error(self): - """ - test_federated_query_notices_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = ['testString'] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_ids": collection_ids, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.federated_query_notices(**req_copy) - - def test_federated_query_notices_value_error_with_retries(self): - # Enable retries and run test_federated_query_notices_value_error. - _service.enable_retries() - self.test_federated_query_notices_value_error() - - # Disable retries and run test_federated_query_notices_value_error. - _service.disable_retries() - self.test_federated_query_notices_value_error() - - -class TestGetAutocompletion: - """ - Test Class for get_autocompletion - """ - - @responses.activate - def test_get_autocompletion_all_params(self): - """ - get_autocompletion() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') - mock_response = '{"completions": ["completions"]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - prefix = 'testString' - field = 'testString' - count = 5 - - # Invoke method - response = _service.get_autocompletion( - environment_id, - collection_id, - prefix, - field=field, - count=count, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'prefix={}'.format(prefix) in query_string - assert 'field={}'.format(field) in query_string - assert 'count={}'.format(count) in query_string - - def test_get_autocompletion_all_params_with_retries(self): - # Enable retries and run test_get_autocompletion_all_params. - _service.enable_retries() - self.test_get_autocompletion_all_params() - - # Disable retries and run test_get_autocompletion_all_params. - _service.disable_retries() - self.test_get_autocompletion_all_params() - - @responses.activate - def test_get_autocompletion_required_params(self): - """ - test_get_autocompletion_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') - mock_response = '{"completions": ["completions"]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - prefix = 'testString' - - # Invoke method - response = _service.get_autocompletion( - environment_id, - collection_id, - prefix, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'prefix={}'.format(prefix) in query_string - - def test_get_autocompletion_required_params_with_retries(self): - # Enable retries and run test_get_autocompletion_required_params. - _service.enable_retries() - self.test_get_autocompletion_required_params() - - # Disable retries and run test_get_autocompletion_required_params. - _service.disable_retries() - self.test_get_autocompletion_required_params() - - @responses.activate - def test_get_autocompletion_value_error(self): - """ - test_get_autocompletion_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') - mock_response = '{"completions": ["completions"]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - prefix = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "prefix": prefix, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_autocompletion(**req_copy) - - def test_get_autocompletion_value_error_with_retries(self): - # Enable retries and run test_get_autocompletion_value_error. - _service.enable_retries() - self.test_get_autocompletion_value_error() - - # Disable retries and run test_get_autocompletion_value_error. - _service.disable_retries() - self.test_get_autocompletion_value_error() - - -# endregion -############################################################################## -# End of Service: Queries -############################################################################## - -############################################################################## -# Start of Service: TrainingData -############################################################################## -# region - - -class TestListTrainingData: - """ - Test Class for list_training_data - """ - - @responses.activate - def test_list_training_data_all_params(self): - """ - list_training_data() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.list_training_data( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_training_data_all_params_with_retries(self): - # Enable retries and run test_list_training_data_all_params. - _service.enable_retries() - self.test_list_training_data_all_params() - - # Disable retries and run test_list_training_data_all_params. - _service.disable_retries() - self.test_list_training_data_all_params() - - @responses.activate - def test_list_training_data_value_error(self): - """ - test_list_training_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_training_data(**req_copy) - - def test_list_training_data_value_error_with_retries(self): - # Enable retries and run test_list_training_data_value_error. - _service.enable_retries() - self.test_list_training_data_value_error() - - # Disable retries and run test_list_training_data_value_error. - _service.disable_retries() - self.test_list_training_data_value_error() - - -class TestAddTrainingData: - """ - Test Class for add_training_data - """ - - @responses.activate - def test_add_training_data_all_params(self): - """ - add_training_data() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a TrainingExample model - training_example_model = {} - training_example_model['document_id'] = 'testString' - training_example_model['cross_reference'] = 'testString' - training_example_model['relevance'] = 38 - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - natural_language_query = 'testString' - filter = 'testString' - examples = [training_example_model] - - # Invoke method - response = _service.add_training_data( - environment_id, - collection_id, - natural_language_query=natural_language_query, - filter=filter, - examples=examples, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['natural_language_query'] == 'testString' - assert req_body['filter'] == 'testString' - assert req_body['examples'] == [training_example_model] - - def test_add_training_data_all_params_with_retries(self): - # Enable retries and run test_add_training_data_all_params. - _service.enable_retries() - self.test_add_training_data_all_params() - - # Disable retries and run test_add_training_data_all_params. - _service.disable_retries() - self.test_add_training_data_all_params() - - @responses.activate - def test_add_training_data_value_error(self): - """ - test_add_training_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a TrainingExample model - training_example_model = {} - training_example_model['document_id'] = 'testString' - training_example_model['cross_reference'] = 'testString' - training_example_model['relevance'] = 38 - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - natural_language_query = 'testString' - filter = 'testString' - examples = [training_example_model] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.add_training_data(**req_copy) - - def test_add_training_data_value_error_with_retries(self): - # Enable retries and run test_add_training_data_value_error. - _service.enable_retries() - self.test_add_training_data_value_error() - - # Disable retries and run test_add_training_data_value_error. - _service.disable_retries() - self.test_add_training_data_value_error() - - -class TestDeleteAllTrainingData: - """ - Test Class for delete_all_training_data - """ - - @responses.activate - def test_delete_all_training_data_all_params(self): - """ - delete_all_training_data() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.delete_all_training_data( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 204 - - def test_delete_all_training_data_all_params_with_retries(self): - # Enable retries and run test_delete_all_training_data_all_params. - _service.enable_retries() - self.test_delete_all_training_data_all_params() - - # Disable retries and run test_delete_all_training_data_all_params. - _service.disable_retries() - self.test_delete_all_training_data_all_params() - - @responses.activate - def test_delete_all_training_data_value_error(self): - """ - test_delete_all_training_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_all_training_data(**req_copy) - - def test_delete_all_training_data_value_error_with_retries(self): - # Enable retries and run test_delete_all_training_data_value_error. - _service.enable_retries() - self.test_delete_all_training_data_value_error() - - # Disable retries and run test_delete_all_training_data_value_error. - _service.disable_retries() - self.test_delete_all_training_data_value_error() - - -class TestGetTrainingData: - """ - Test Class for get_training_data - """ - - @responses.activate - def test_get_training_data_all_params(self): - """ - get_training_data() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Invoke method - response = _service.get_training_data( - environment_id, - collection_id, - query_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_training_data_all_params_with_retries(self): - # Enable retries and run test_get_training_data_all_params. - _service.enable_retries() - self.test_get_training_data_all_params() - - # Disable retries and run test_get_training_data_all_params. - _service.disable_retries() - self.test_get_training_data_all_params() - - @responses.activate - def test_get_training_data_value_error(self): - """ - test_get_training_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_training_data(**req_copy) - - def test_get_training_data_value_error_with_retries(self): - # Enable retries and run test_get_training_data_value_error. - _service.enable_retries() - self.test_get_training_data_value_error() - - # Disable retries and run test_get_training_data_value_error. - _service.disable_retries() - self.test_get_training_data_value_error() - - -class TestDeleteTrainingData: - """ - Test Class for delete_training_data - """ - - @responses.activate - def test_delete_training_data_all_params(self): - """ - delete_training_data() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Invoke method - response = _service.delete_training_data( - environment_id, - collection_id, - query_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 204 - - def test_delete_training_data_all_params_with_retries(self): - # Enable retries and run test_delete_training_data_all_params. - _service.enable_retries() - self.test_delete_training_data_all_params() - - # Disable retries and run test_delete_training_data_all_params. - _service.disable_retries() - self.test_delete_training_data_all_params() - - @responses.activate - def test_delete_training_data_value_error(self): - """ - test_delete_training_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_training_data(**req_copy) - - def test_delete_training_data_value_error_with_retries(self): - # Enable retries and run test_delete_training_data_value_error. - _service.enable_retries() - self.test_delete_training_data_value_error() - - # Disable retries and run test_delete_training_data_value_error. - _service.disable_retries() - self.test_delete_training_data_value_error() - - -class TestListTrainingExamples: - """ - Test Class for list_training_examples - """ - - @responses.activate - def test_list_training_examples_all_params(self): - """ - list_training_examples() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') - mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Invoke method - response = _service.list_training_examples( - environment_id, - collection_id, - query_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_training_examples_all_params_with_retries(self): - # Enable retries and run test_list_training_examples_all_params. - _service.enable_retries() - self.test_list_training_examples_all_params() - - # Disable retries and run test_list_training_examples_all_params. - _service.disable_retries() - self.test_list_training_examples_all_params() - - @responses.activate - def test_list_training_examples_value_error(self): - """ - test_list_training_examples_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') - mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_training_examples(**req_copy) - - def test_list_training_examples_value_error_with_retries(self): - # Enable retries and run test_list_training_examples_value_error. - _service.enable_retries() - self.test_list_training_examples_value_error() - - # Disable retries and run test_list_training_examples_value_error. - _service.disable_retries() - self.test_list_training_examples_value_error() - - -class TestCreateTrainingExample: - """ - Test Class for create_training_example - """ - - @responses.activate - def test_create_training_example_all_params(self): - """ - create_training_example() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - document_id = 'testString' - cross_reference = 'testString' - relevance = 38 - - # Invoke method - response = _service.create_training_example( - environment_id, - collection_id, - query_id, - document_id=document_id, - cross_reference=cross_reference, - relevance=relevance, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['document_id'] == 'testString' - assert req_body['cross_reference'] == 'testString' - assert req_body['relevance'] == 38 - - def test_create_training_example_all_params_with_retries(self): - # Enable retries and run test_create_training_example_all_params. - _service.enable_retries() - self.test_create_training_example_all_params() - - # Disable retries and run test_create_training_example_all_params. - _service.disable_retries() - self.test_create_training_example_all_params() - - @responses.activate - def test_create_training_example_value_error(self): - """ - test_create_training_example_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - document_id = 'testString' - cross_reference = 'testString' - relevance = 38 - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_training_example(**req_copy) - - def test_create_training_example_value_error_with_retries(self): - # Enable retries and run test_create_training_example_value_error. - _service.enable_retries() - self.test_create_training_example_value_error() - - # Disable retries and run test_create_training_example_value_error. - _service.disable_retries() - self.test_create_training_example_value_error() - - -class TestDeleteTrainingExample: - """ - Test Class for delete_training_example - """ - - @responses.activate - def test_delete_training_example_all_params(self): - """ - delete_training_example() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - - # Invoke method - response = _service.delete_training_example( - environment_id, - collection_id, - query_id, - example_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 204 - - def test_delete_training_example_all_params_with_retries(self): - # Enable retries and run test_delete_training_example_all_params. - _service.enable_retries() - self.test_delete_training_example_all_params() - - # Disable retries and run test_delete_training_example_all_params. - _service.disable_retries() - self.test_delete_training_example_all_params() - - @responses.activate - def test_delete_training_example_value_error(self): - """ - test_delete_training_example_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - "example_id": example_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_training_example(**req_copy) - - def test_delete_training_example_value_error_with_retries(self): - # Enable retries and run test_delete_training_example_value_error. - _service.enable_retries() - self.test_delete_training_example_value_error() - - # Disable retries and run test_delete_training_example_value_error. - _service.disable_retries() - self.test_delete_training_example_value_error() - - -class TestUpdateTrainingExample: - """ - Test Class for update_training_example - """ - - @responses.activate - def test_update_training_example_all_params(self): - """ - update_training_example() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - cross_reference = 'testString' - relevance = 38 - - # Invoke method - response = _service.update_training_example( - environment_id, - collection_id, - query_id, - example_id, - cross_reference=cross_reference, - relevance=relevance, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['cross_reference'] == 'testString' - assert req_body['relevance'] == 38 - - def test_update_training_example_all_params_with_retries(self): - # Enable retries and run test_update_training_example_all_params. - _service.enable_retries() - self.test_update_training_example_all_params() - - # Disable retries and run test_update_training_example_all_params. - _service.disable_retries() - self.test_update_training_example_all_params() - - @responses.activate - def test_update_training_example_value_error(self): - """ - test_update_training_example_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - cross_reference = 'testString' - relevance = 38 - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - "example_id": example_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_training_example(**req_copy) - - def test_update_training_example_value_error_with_retries(self): - # Enable retries and run test_update_training_example_value_error. - _service.enable_retries() - self.test_update_training_example_value_error() - - # Disable retries and run test_update_training_example_value_error. - _service.disable_retries() - self.test_update_training_example_value_error() - - -class TestGetTrainingExample: - """ - Test Class for get_training_example - """ - - @responses.activate - def test_get_training_example_all_params(self): - """ - get_training_example() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - - # Invoke method - response = _service.get_training_example( - environment_id, - collection_id, - query_id, - example_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_training_example_all_params_with_retries(self): - # Enable retries and run test_get_training_example_all_params. - _service.enable_retries() - self.test_get_training_example_all_params() - - # Disable retries and run test_get_training_example_all_params. - _service.disable_retries() - self.test_get_training_example_all_params() - - @responses.activate - def test_get_training_example_value_error(self): - """ - test_get_training_example_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - "example_id": example_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_training_example(**req_copy) - - def test_get_training_example_value_error_with_retries(self): - # Enable retries and run test_get_training_example_value_error. - _service.enable_retries() - self.test_get_training_example_value_error() - - # Disable retries and run test_get_training_example_value_error. - _service.disable_retries() - self.test_get_training_example_value_error() - - -# endregion -############################################################################## -# End of Service: TrainingData -############################################################################## - -############################################################################## -# Start of Service: UserData -############################################################################## -# region - - -class TestDeleteUserData: - """ - Test Class for delete_user_data - """ - - @responses.activate - def test_delete_user_data_all_params(self): - """ - delete_user_data() - """ - # Set up mock - url = preprocess_url('/v1/user_data') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - customer_id = 'testString' - - # Invoke method - response = _service.delete_user_data( - customer_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'customer_id={}'.format(customer_id) in query_string - - def test_delete_user_data_all_params_with_retries(self): - # Enable retries and run test_delete_user_data_all_params. - _service.enable_retries() - self.test_delete_user_data_all_params() - - # Disable retries and run test_delete_user_data_all_params. - _service.disable_retries() - self.test_delete_user_data_all_params() - - @responses.activate - def test_delete_user_data_value_error(self): - """ - test_delete_user_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/user_data') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - customer_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "customer_id": customer_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_user_data(**req_copy) - - def test_delete_user_data_value_error_with_retries(self): - # Enable retries and run test_delete_user_data_value_error. - _service.enable_retries() - self.test_delete_user_data_value_error() - - # Disable retries and run test_delete_user_data_value_error. - _service.disable_retries() - self.test_delete_user_data_value_error() - - -# endregion -############################################################################## -# End of Service: UserData -############################################################################## - -############################################################################## -# Start of Service: EventsAndFeedback -############################################################################## -# region - - -class TestCreateEvent: - """ - Test Class for create_event - """ - - @responses.activate - def test_create_event_all_params(self): - """ - create_event() - """ - # Set up mock - url = preprocess_url('/v1/events') - mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Construct a dict representation of a EventData model - event_data_model = {} - event_data_model['environment_id'] = 'testString' - event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = '2019-01-01T12:00:00Z' - event_data_model['display_rank'] = 38 - event_data_model['collection_id'] = 'testString' - event_data_model['document_id'] = 'testString' - - # Set up parameter values - type = 'click' - data = event_data_model - - # Invoke method - response = _service.create_event( - type, - data, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['type'] == 'click' - assert req_body['data'] == event_data_model - - def test_create_event_all_params_with_retries(self): - # Enable retries and run test_create_event_all_params. - _service.enable_retries() - self.test_create_event_all_params() - - # Disable retries and run test_create_event_all_params. - _service.disable_retries() - self.test_create_event_all_params() - - @responses.activate - def test_create_event_value_error(self): - """ - test_create_event_value_error() - """ - # Set up mock - url = preprocess_url('/v1/events') - mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Construct a dict representation of a EventData model - event_data_model = {} - event_data_model['environment_id'] = 'testString' - event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = '2019-01-01T12:00:00Z' - event_data_model['display_rank'] = 38 - event_data_model['collection_id'] = 'testString' - event_data_model['document_id'] = 'testString' - - # Set up parameter values - type = 'click' - data = event_data_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "type": type, - "data": data, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_event(**req_copy) - - def test_create_event_value_error_with_retries(self): - # Enable retries and run test_create_event_value_error. - _service.enable_retries() - self.test_create_event_value_error() - - # Disable retries and run test_create_event_value_error. - _service.disable_retries() - self.test_create_event_value_error() - - -class TestQueryLog: - """ - Test Class for query_log - """ - - @responses.activate - def test_query_log_all_params(self): - """ - query_log() - """ - # Set up mock - url = preprocess_url('/v1/logs') - mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - filter = 'testString' - query = 'testString' - count = 10 - offset = 38 - sort = ['testString'] - - # Invoke method - response = _service.query_log( - filter=filter, - query=query, - count=count, - offset=offset, - sort=sort, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'filter={}'.format(filter) in query_string - assert 'query={}'.format(query) in query_string - assert 'count={}'.format(count) in query_string - assert 'offset={}'.format(offset) in query_string - assert 'sort={}'.format(','.join(sort)) in query_string - - def test_query_log_all_params_with_retries(self): - # Enable retries and run test_query_log_all_params. - _service.enable_retries() - self.test_query_log_all_params() - - # Disable retries and run test_query_log_all_params. - _service.disable_retries() - self.test_query_log_all_params() - - @responses.activate - def test_query_log_required_params(self): - """ - test_query_log_required_params() - """ - # Set up mock - url = preprocess_url('/v1/logs') - mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.query_log() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_query_log_required_params_with_retries(self): - # Enable retries and run test_query_log_required_params. - _service.enable_retries() - self.test_query_log_required_params() - - # Disable retries and run test_query_log_required_params. - _service.disable_retries() - self.test_query_log_required_params() - - @responses.activate - def test_query_log_value_error(self): - """ - test_query_log_value_error() - """ - # Set up mock - url = preprocess_url('/v1/logs') - mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.query_log(**req_copy) - - def test_query_log_value_error_with_retries(self): - # Enable retries and run test_query_log_value_error. - _service.enable_retries() - self.test_query_log_value_error() - - # Disable retries and run test_query_log_value_error. - _service.disable_retries() - self.test_query_log_value_error() - - -class TestGetMetricsQuery: - """ - Test Class for get_metrics_query - """ - - @responses.activate - def test_get_metrics_query_all_params(self): - """ - get_metrics_query() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - start_time = string_to_datetime('2019-01-01T12:00:00.000Z') - end_time = string_to_datetime('2019-01-01T12:00:00.000Z') - result_type = 'document' - - # Invoke method - response = _service.get_metrics_query( - start_time=start_time, - end_time=end_time, - result_type=result_type, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'result_type={}'.format(result_type) in query_string - - def test_get_metrics_query_all_params_with_retries(self): - # Enable retries and run test_get_metrics_query_all_params. - _service.enable_retries() - self.test_get_metrics_query_all_params() - - # Disable retries and run test_get_metrics_query_all_params. - _service.disable_retries() - self.test_get_metrics_query_all_params() - - @responses.activate - def test_get_metrics_query_required_params(self): - """ - test_get_metrics_query_required_params() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.get_metrics_query() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_metrics_query_required_params_with_retries(self): - # Enable retries and run test_get_metrics_query_required_params. - _service.enable_retries() - self.test_get_metrics_query_required_params() - - # Disable retries and run test_get_metrics_query_required_params. - _service.disable_retries() - self.test_get_metrics_query_required_params() - - @responses.activate - def test_get_metrics_query_value_error(self): - """ - test_get_metrics_query_value_error() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_metrics_query(**req_copy) - - def test_get_metrics_query_value_error_with_retries(self): - # Enable retries and run test_get_metrics_query_value_error. - _service.enable_retries() - self.test_get_metrics_query_value_error() - - # Disable retries and run test_get_metrics_query_value_error. - _service.disable_retries() - self.test_get_metrics_query_value_error() - - -class TestGetMetricsQueryEvent: - """ - Test Class for get_metrics_query_event - """ - - @responses.activate - def test_get_metrics_query_event_all_params(self): - """ - get_metrics_query_event() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_event') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - start_time = string_to_datetime('2019-01-01T12:00:00.000Z') - end_time = string_to_datetime('2019-01-01T12:00:00.000Z') - result_type = 'document' - - # Invoke method - response = _service.get_metrics_query_event( - start_time=start_time, - end_time=end_time, - result_type=result_type, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'result_type={}'.format(result_type) in query_string - - def test_get_metrics_query_event_all_params_with_retries(self): - # Enable retries and run test_get_metrics_query_event_all_params. - _service.enable_retries() - self.test_get_metrics_query_event_all_params() - - # Disable retries and run test_get_metrics_query_event_all_params. - _service.disable_retries() - self.test_get_metrics_query_event_all_params() - - @responses.activate - def test_get_metrics_query_event_required_params(self): - """ - test_get_metrics_query_event_required_params() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_event') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.get_metrics_query_event() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_metrics_query_event_required_params_with_retries(self): - # Enable retries and run test_get_metrics_query_event_required_params. - _service.enable_retries() - self.test_get_metrics_query_event_required_params() - - # Disable retries and run test_get_metrics_query_event_required_params. - _service.disable_retries() - self.test_get_metrics_query_event_required_params() - - @responses.activate - def test_get_metrics_query_event_value_error(self): - """ - test_get_metrics_query_event_value_error() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_event') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_metrics_query_event(**req_copy) - - def test_get_metrics_query_event_value_error_with_retries(self): - # Enable retries and run test_get_metrics_query_event_value_error. - _service.enable_retries() - self.test_get_metrics_query_event_value_error() - - # Disable retries and run test_get_metrics_query_event_value_error. - _service.disable_retries() - self.test_get_metrics_query_event_value_error() - - -class TestGetMetricsQueryNoResults: - """ - Test Class for get_metrics_query_no_results - """ - - @responses.activate - def test_get_metrics_query_no_results_all_params(self): - """ - get_metrics_query_no_results() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - start_time = string_to_datetime('2019-01-01T12:00:00.000Z') - end_time = string_to_datetime('2019-01-01T12:00:00.000Z') - result_type = 'document' - - # Invoke method - response = _service.get_metrics_query_no_results( - start_time=start_time, - end_time=end_time, - result_type=result_type, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'result_type={}'.format(result_type) in query_string - - def test_get_metrics_query_no_results_all_params_with_retries(self): - # Enable retries and run test_get_metrics_query_no_results_all_params. - _service.enable_retries() - self.test_get_metrics_query_no_results_all_params() - - # Disable retries and run test_get_metrics_query_no_results_all_params. - _service.disable_retries() - self.test_get_metrics_query_no_results_all_params() - - @responses.activate - def test_get_metrics_query_no_results_required_params(self): - """ - test_get_metrics_query_no_results_required_params() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.get_metrics_query_no_results() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_metrics_query_no_results_required_params_with_retries(self): - # Enable retries and run test_get_metrics_query_no_results_required_params. - _service.enable_retries() - self.test_get_metrics_query_no_results_required_params() - - # Disable retries and run test_get_metrics_query_no_results_required_params. - _service.disable_retries() - self.test_get_metrics_query_no_results_required_params() - - @responses.activate - def test_get_metrics_query_no_results_value_error(self): - """ - test_get_metrics_query_no_results_value_error() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_metrics_query_no_results(**req_copy) - - def test_get_metrics_query_no_results_value_error_with_retries(self): - # Enable retries and run test_get_metrics_query_no_results_value_error. - _service.enable_retries() - self.test_get_metrics_query_no_results_value_error() - - # Disable retries and run test_get_metrics_query_no_results_value_error. - _service.disable_retries() - self.test_get_metrics_query_no_results_value_error() - - -class TestGetMetricsEventRate: - """ - Test Class for get_metrics_event_rate - """ - - @responses.activate - def test_get_metrics_event_rate_all_params(self): - """ - get_metrics_event_rate() - """ - # Set up mock - url = preprocess_url('/v1/metrics/event_rate') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - start_time = string_to_datetime('2019-01-01T12:00:00.000Z') - end_time = string_to_datetime('2019-01-01T12:00:00.000Z') - result_type = 'document' - - # Invoke method - response = _service.get_metrics_event_rate( - start_time=start_time, - end_time=end_time, - result_type=result_type, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'result_type={}'.format(result_type) in query_string - - def test_get_metrics_event_rate_all_params_with_retries(self): - # Enable retries and run test_get_metrics_event_rate_all_params. - _service.enable_retries() - self.test_get_metrics_event_rate_all_params() - - # Disable retries and run test_get_metrics_event_rate_all_params. - _service.disable_retries() - self.test_get_metrics_event_rate_all_params() - - @responses.activate - def test_get_metrics_event_rate_required_params(self): - """ - test_get_metrics_event_rate_required_params() - """ - # Set up mock - url = preprocess_url('/v1/metrics/event_rate') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.get_metrics_event_rate() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_metrics_event_rate_required_params_with_retries(self): - # Enable retries and run test_get_metrics_event_rate_required_params. - _service.enable_retries() - self.test_get_metrics_event_rate_required_params() - - # Disable retries and run test_get_metrics_event_rate_required_params. - _service.disable_retries() - self.test_get_metrics_event_rate_required_params() - - @responses.activate - def test_get_metrics_event_rate_value_error(self): - """ - test_get_metrics_event_rate_value_error() - """ - # Set up mock - url = preprocess_url('/v1/metrics/event_rate') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_metrics_event_rate(**req_copy) - - def test_get_metrics_event_rate_value_error_with_retries(self): - # Enable retries and run test_get_metrics_event_rate_value_error. - _service.enable_retries() - self.test_get_metrics_event_rate_value_error() - - # Disable retries and run test_get_metrics_event_rate_value_error. - _service.disable_retries() - self.test_get_metrics_event_rate_value_error() - - -class TestGetMetricsQueryTokenEvent: - """ - Test Class for get_metrics_query_token_event - """ - - @responses.activate - def test_get_metrics_query_token_event_all_params(self): - """ - get_metrics_query_token_event() - """ - # Set up mock - url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') - mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - count = 10 - - # Invoke method - response = _service.get_metrics_query_token_event( - count=count, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'count={}'.format(count) in query_string - - def test_get_metrics_query_token_event_all_params_with_retries(self): - # Enable retries and run test_get_metrics_query_token_event_all_params. - _service.enable_retries() - self.test_get_metrics_query_token_event_all_params() - - # Disable retries and run test_get_metrics_query_token_event_all_params. - _service.disable_retries() - self.test_get_metrics_query_token_event_all_params() - - @responses.activate - def test_get_metrics_query_token_event_required_params(self): - """ - test_get_metrics_query_token_event_required_params() - """ - # Set up mock - url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') - mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.get_metrics_query_token_event() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_metrics_query_token_event_required_params_with_retries(self): - # Enable retries and run test_get_metrics_query_token_event_required_params. - _service.enable_retries() - self.test_get_metrics_query_token_event_required_params() - - # Disable retries and run test_get_metrics_query_token_event_required_params. - _service.disable_retries() - self.test_get_metrics_query_token_event_required_params() - - @responses.activate - def test_get_metrics_query_token_event_value_error(self): - """ - test_get_metrics_query_token_event_value_error() - """ - # Set up mock - url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') - mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_metrics_query_token_event(**req_copy) - - def test_get_metrics_query_token_event_value_error_with_retries(self): - # Enable retries and run test_get_metrics_query_token_event_value_error. - _service.enable_retries() - self.test_get_metrics_query_token_event_value_error() - - # Disable retries and run test_get_metrics_query_token_event_value_error. - _service.disable_retries() - self.test_get_metrics_query_token_event_value_error() - - -# endregion -############################################################################## -# End of Service: EventsAndFeedback -############################################################################## - -############################################################################## -# Start of Service: Credentials -############################################################################## -# region - - -class TestListCredentials: - """ - Test Class for list_credentials - """ - - @responses.activate - def test_list_credentials_all_params(self): - """ - list_credentials() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials') - mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.list_credentials( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_credentials_all_params_with_retries(self): - # Enable retries and run test_list_credentials_all_params. - _service.enable_retries() - self.test_list_credentials_all_params() - - # Disable retries and run test_list_credentials_all_params. - _service.disable_retries() - self.test_list_credentials_all_params() - - @responses.activate - def test_list_credentials_value_error(self): - """ - test_list_credentials_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials') - mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_credentials(**req_copy) - - def test_list_credentials_value_error_with_retries(self): - # Enable retries and run test_list_credentials_value_error. - _service.enable_retries() - self.test_list_credentials_value_error() - - # Disable retries and run test_list_credentials_value_error. - _service.disable_retries() - self.test_list_credentials_value_error() - - -class TestCreateCredentials: - """ - Test Class for create_credentials - """ - - @responses.activate - def test_create_credentials_all_params(self): - """ - create_credentials() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a CredentialDetails model - credential_details_model = {} - credential_details_model['credential_type'] = 'oauth2' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'testString' - credential_details_model['username'] = 'testString' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - # Construct a dict representation of a StatusDetails model - status_details_model = {} - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - # Set up parameter values - environment_id = 'testString' - source_type = 'box' - credential_details = credential_details_model - status = status_details_model - - # Invoke method - response = _service.create_credentials( - environment_id, - source_type=source_type, - credential_details=credential_details, - status=status, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['source_type'] == 'box' - assert req_body['credential_details'] == credential_details_model - assert req_body['status'] == status_details_model - - def test_create_credentials_all_params_with_retries(self): - # Enable retries and run test_create_credentials_all_params. - _service.enable_retries() - self.test_create_credentials_all_params() - - # Disable retries and run test_create_credentials_all_params. - _service.disable_retries() - self.test_create_credentials_all_params() - - @responses.activate - def test_create_credentials_value_error(self): - """ - test_create_credentials_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a CredentialDetails model - credential_details_model = {} - credential_details_model['credential_type'] = 'oauth2' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'testString' - credential_details_model['username'] = 'testString' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - # Construct a dict representation of a StatusDetails model - status_details_model = {} - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - # Set up parameter values - environment_id = 'testString' - source_type = 'box' - credential_details = credential_details_model - status = status_details_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_credentials(**req_copy) - - def test_create_credentials_value_error_with_retries(self): - # Enable retries and run test_create_credentials_value_error. - _service.enable_retries() - self.test_create_credentials_value_error() - - # Disable retries and run test_create_credentials_value_error. - _service.disable_retries() - self.test_create_credentials_value_error() - - -class TestGetCredentials: - """ - Test Class for get_credentials - """ - - @responses.activate - def test_get_credentials_all_params(self): - """ - get_credentials() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - - # Invoke method - response = _service.get_credentials( - environment_id, - credential_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_credentials_all_params_with_retries(self): - # Enable retries and run test_get_credentials_all_params. - _service.enable_retries() - self.test_get_credentials_all_params() - - # Disable retries and run test_get_credentials_all_params. - _service.disable_retries() - self.test_get_credentials_all_params() - - @responses.activate - def test_get_credentials_value_error(self): - """ - test_get_credentials_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "credential_id": credential_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_credentials(**req_copy) - - def test_get_credentials_value_error_with_retries(self): - # Enable retries and run test_get_credentials_value_error. - _service.enable_retries() - self.test_get_credentials_value_error() - - # Disable retries and run test_get_credentials_value_error. - _service.disable_retries() - self.test_get_credentials_value_error() - - -class TestUpdateCredentials: - """ - Test Class for update_credentials - """ - - @responses.activate - def test_update_credentials_all_params(self): - """ - update_credentials() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a CredentialDetails model - credential_details_model = {} - credential_details_model['credential_type'] = 'oauth2' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'testString' - credential_details_model['username'] = 'testString' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - # Construct a dict representation of a StatusDetails model - status_details_model = {} - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - source_type = 'box' - credential_details = credential_details_model - status = status_details_model - - # Invoke method - response = _service.update_credentials( - environment_id, - credential_id, - source_type=source_type, - credential_details=credential_details, - status=status, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['source_type'] == 'box' - assert req_body['credential_details'] == credential_details_model - assert req_body['status'] == status_details_model - - def test_update_credentials_all_params_with_retries(self): - # Enable retries and run test_update_credentials_all_params. - _service.enable_retries() - self.test_update_credentials_all_params() - - # Disable retries and run test_update_credentials_all_params. - _service.disable_retries() - self.test_update_credentials_all_params() - - @responses.activate - def test_update_credentials_value_error(self): - """ - test_update_credentials_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a CredentialDetails model - credential_details_model = {} - credential_details_model['credential_type'] = 'oauth2' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'testString' - credential_details_model['username'] = 'testString' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - # Construct a dict representation of a StatusDetails model - status_details_model = {} - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - source_type = 'box' - credential_details = credential_details_model - status = status_details_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "credential_id": credential_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_credentials(**req_copy) - - def test_update_credentials_value_error_with_retries(self): - # Enable retries and run test_update_credentials_value_error. - _service.enable_retries() - self.test_update_credentials_value_error() - - # Disable retries and run test_update_credentials_value_error. - _service.disable_retries() - self.test_update_credentials_value_error() - - -class TestDeleteCredentials: - """ - Test Class for delete_credentials - """ - - @responses.activate - def test_delete_credentials_all_params(self): - """ - delete_credentials() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - - # Invoke method - response = _service.delete_credentials( - environment_id, - credential_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_credentials_all_params_with_retries(self): - # Enable retries and run test_delete_credentials_all_params. - _service.enable_retries() - self.test_delete_credentials_all_params() - - # Disable retries and run test_delete_credentials_all_params. - _service.disable_retries() - self.test_delete_credentials_all_params() - - @responses.activate - def test_delete_credentials_value_error(self): - """ - test_delete_credentials_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "credential_id": credential_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_credentials(**req_copy) - - def test_delete_credentials_value_error_with_retries(self): - # Enable retries and run test_delete_credentials_value_error. - _service.enable_retries() - self.test_delete_credentials_value_error() - - # Disable retries and run test_delete_credentials_value_error. - _service.disable_retries() - self.test_delete_credentials_value_error() - - -# endregion -############################################################################## -# End of Service: Credentials -############################################################################## - -############################################################################## -# Start of Service: GatewayConfiguration -############################################################################## -# region - - -class TestListGateways: - """ - Test Class for list_gateways - """ - - @responses.activate - def test_list_gateways_all_params(self): - """ - list_gateways() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways') - mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.list_gateways( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_gateways_all_params_with_retries(self): - # Enable retries and run test_list_gateways_all_params. - _service.enable_retries() - self.test_list_gateways_all_params() - - # Disable retries and run test_list_gateways_all_params. - _service.disable_retries() - self.test_list_gateways_all_params() - - @responses.activate - def test_list_gateways_value_error(self): - """ - test_list_gateways_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways') - mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_gateways(**req_copy) - - def test_list_gateways_value_error_with_retries(self): - # Enable retries and run test_list_gateways_value_error. - _service.enable_retries() - self.test_list_gateways_value_error() - - # Disable retries and run test_list_gateways_value_error. - _service.disable_retries() - self.test_list_gateways_value_error() - - -class TestCreateGateway: - """ - Test Class for create_gateway - """ - - @responses.activate - def test_create_gateway_all_params(self): - """ - create_gateway() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways') - mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - - # Invoke method - response = _service.create_gateway( - environment_id, - name=name, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - - def test_create_gateway_all_params_with_retries(self): - # Enable retries and run test_create_gateway_all_params. - _service.enable_retries() - self.test_create_gateway_all_params() - - # Disable retries and run test_create_gateway_all_params. - _service.disable_retries() - self.test_create_gateway_all_params() - - @responses.activate - def test_create_gateway_required_params(self): - """ - test_create_gateway_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways') - mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.create_gateway( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_create_gateway_required_params_with_retries(self): - # Enable retries and run test_create_gateway_required_params. - _service.enable_retries() - self.test_create_gateway_required_params() - - # Disable retries and run test_create_gateway_required_params. - _service.disable_retries() - self.test_create_gateway_required_params() - - @responses.activate - def test_create_gateway_value_error(self): - """ - test_create_gateway_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways') - mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_gateway(**req_copy) - - def test_create_gateway_value_error_with_retries(self): - # Enable retries and run test_create_gateway_value_error. - _service.enable_retries() - self.test_create_gateway_value_error() - - # Disable retries and run test_create_gateway_value_error. - _service.disable_retries() - self.test_create_gateway_value_error() - - -class TestGetGateway: - """ - Test Class for get_gateway - """ - - @responses.activate - def test_get_gateway_all_params(self): - """ - get_gateway() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways/testString') - mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - gateway_id = 'testString' - - # Invoke method - response = _service.get_gateway( - environment_id, - gateway_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_gateway_all_params_with_retries(self): - # Enable retries and run test_get_gateway_all_params. - _service.enable_retries() - self.test_get_gateway_all_params() - - # Disable retries and run test_get_gateway_all_params. - _service.disable_retries() - self.test_get_gateway_all_params() - - @responses.activate - def test_get_gateway_value_error(self): - """ - test_get_gateway_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways/testString') - mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - gateway_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "gateway_id": gateway_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_gateway(**req_copy) - - def test_get_gateway_value_error_with_retries(self): - # Enable retries and run test_get_gateway_value_error. - _service.enable_retries() - self.test_get_gateway_value_error() - - # Disable retries and run test_get_gateway_value_error. - _service.disable_retries() - self.test_get_gateway_value_error() - - -class TestDeleteGateway: - """ - Test Class for delete_gateway - """ - - @responses.activate - def test_delete_gateway_all_params(self): - """ - delete_gateway() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways/testString') - mock_response = '{"gateway_id": "gateway_id", "status": "status"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - gateway_id = 'testString' - - # Invoke method - response = _service.delete_gateway( - environment_id, - gateway_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_gateway_all_params_with_retries(self): - # Enable retries and run test_delete_gateway_all_params. - _service.enable_retries() - self.test_delete_gateway_all_params() - - # Disable retries and run test_delete_gateway_all_params. - _service.disable_retries() - self.test_delete_gateway_all_params() - - @responses.activate - def test_delete_gateway_value_error(self): - """ - test_delete_gateway_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways/testString') - mock_response = '{"gateway_id": "gateway_id", "status": "status"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - gateway_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "gateway_id": gateway_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_gateway(**req_copy) - - def test_delete_gateway_value_error_with_retries(self): - # Enable retries and run test_delete_gateway_value_error. - _service.enable_retries() - self.test_delete_gateway_value_error() - - # Disable retries and run test_delete_gateway_value_error. - _service.disable_retries() - self.test_delete_gateway_value_error() - - -# endregion -############################################################################## -# End of Service: GatewayConfiguration -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region - - -class TestModel_Collection: - """ - Test Class for Collection - """ - - def test_collection_serialization(self): - """ - Test serialization/deserialization for Collection - """ - - # Construct dict forms of any model objects needed in order to build this model. - - document_counts_model = {} # DocumentCounts - - collection_disk_usage_model = {} # CollectionDiskUsage - - training_status_model = {} # TrainingStatus - training_status_model['total_examples'] = 0 - training_status_model['available'] = False - training_status_model['processing'] = False - training_status_model['minimum_queries_added'] = False - training_status_model['minimum_examples_added'] = False - training_status_model['sufficient_label_diversity'] = False - training_status_model['notices'] = 0 - training_status_model['successfully_trained'] = '2019-01-01T12:00:00Z' - training_status_model['data_updated'] = '2019-01-01T12:00:00Z' - - source_status_model = {} # SourceStatus - source_status_model['status'] = 'complete' - source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' - - collection_crawl_status_model = {} # CollectionCrawlStatus - collection_crawl_status_model['source_crawl'] = source_status_model - - sdu_status_custom_fields_model = {} # SduStatusCustomFields - sdu_status_custom_fields_model['defined'] = 26 - sdu_status_custom_fields_model['maximum_allowed'] = 5 - - sdu_status_model = {} # SduStatus - sdu_status_model['enabled'] = True - sdu_status_model['total_annotated_pages'] = 0 - sdu_status_model['total_pages'] = 0 - sdu_status_model['total_documents'] = 0 - sdu_status_model['custom_fields'] = sdu_status_custom_fields_model - - # Construct a json representation of a Collection model - collection_model_json = {} - collection_model_json['name'] = 'testString' - collection_model_json['description'] = 'testString' - collection_model_json['configuration_id'] = 'testString' - collection_model_json['language'] = 'testString' - collection_model_json['document_counts'] = document_counts_model - collection_model_json['disk_usage'] = collection_disk_usage_model - collection_model_json['training_status'] = training_status_model - collection_model_json['crawl_status'] = collection_crawl_status_model - collection_model_json['smart_document_understanding'] = sdu_status_model - - # Construct a model instance of Collection by calling from_dict on the json representation - collection_model = Collection.from_dict(collection_model_json) - assert collection_model != False - - # Construct a model instance of Collection by calling from_dict on the json representation - collection_model_dict = Collection.from_dict(collection_model_json).__dict__ - collection_model2 = Collection(**collection_model_dict) - - # Verify the model instances are equivalent - assert collection_model == collection_model2 - - # Convert model instance back to dict and verify no loss of data - collection_model_json2 = collection_model.to_dict() - assert collection_model_json2 == collection_model_json - - -class TestModel_CollectionCrawlStatus: - """ - Test Class for CollectionCrawlStatus - """ - - def test_collection_crawl_status_serialization(self): - """ - Test serialization/deserialization for CollectionCrawlStatus - """ - - # Construct dict forms of any model objects needed in order to build this model. - - source_status_model = {} # SourceStatus - source_status_model['status'] = 'running' - source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' - - # Construct a json representation of a CollectionCrawlStatus model - collection_crawl_status_model_json = {} - collection_crawl_status_model_json['source_crawl'] = source_status_model - - # Construct a model instance of CollectionCrawlStatus by calling from_dict on the json representation - collection_crawl_status_model = CollectionCrawlStatus.from_dict(collection_crawl_status_model_json) - assert collection_crawl_status_model != False - - # Construct a model instance of CollectionCrawlStatus by calling from_dict on the json representation - collection_crawl_status_model_dict = CollectionCrawlStatus.from_dict(collection_crawl_status_model_json).__dict__ - collection_crawl_status_model2 = CollectionCrawlStatus(**collection_crawl_status_model_dict) - - # Verify the model instances are equivalent - assert collection_crawl_status_model == collection_crawl_status_model2 - - # Convert model instance back to dict and verify no loss of data - collection_crawl_status_model_json2 = collection_crawl_status_model.to_dict() - assert collection_crawl_status_model_json2 == collection_crawl_status_model_json - - -class TestModel_CollectionDiskUsage: - """ - Test Class for CollectionDiskUsage - """ - - def test_collection_disk_usage_serialization(self): - """ - Test serialization/deserialization for CollectionDiskUsage - """ - - # Construct a json representation of a CollectionDiskUsage model - collection_disk_usage_model_json = {} - - # Construct a model instance of CollectionDiskUsage by calling from_dict on the json representation - collection_disk_usage_model = CollectionDiskUsage.from_dict(collection_disk_usage_model_json) - assert collection_disk_usage_model != False - - # Construct a model instance of CollectionDiskUsage by calling from_dict on the json representation - collection_disk_usage_model_dict = CollectionDiskUsage.from_dict(collection_disk_usage_model_json).__dict__ - collection_disk_usage_model2 = CollectionDiskUsage(**collection_disk_usage_model_dict) - - # Verify the model instances are equivalent - assert collection_disk_usage_model == collection_disk_usage_model2 - - # Convert model instance back to dict and verify no loss of data - collection_disk_usage_model_json2 = collection_disk_usage_model.to_dict() - assert collection_disk_usage_model_json2 == collection_disk_usage_model_json - - -class TestModel_CollectionUsage: - """ - Test Class for CollectionUsage - """ - - def test_collection_usage_serialization(self): - """ - Test serialization/deserialization for CollectionUsage - """ - - # Construct a json representation of a CollectionUsage model - collection_usage_model_json = {} - - # Construct a model instance of CollectionUsage by calling from_dict on the json representation - collection_usage_model = CollectionUsage.from_dict(collection_usage_model_json) - assert collection_usage_model != False - - # Construct a model instance of CollectionUsage by calling from_dict on the json representation - collection_usage_model_dict = CollectionUsage.from_dict(collection_usage_model_json).__dict__ - collection_usage_model2 = CollectionUsage(**collection_usage_model_dict) - - # Verify the model instances are equivalent - assert collection_usage_model == collection_usage_model2 - - # Convert model instance back to dict and verify no loss of data - collection_usage_model_json2 = collection_usage_model.to_dict() - assert collection_usage_model_json2 == collection_usage_model_json - - -class TestModel_Completions: - """ - Test Class for Completions - """ - - def test_completions_serialization(self): - """ - Test serialization/deserialization for Completions - """ - - # Construct a json representation of a Completions model - completions_model_json = {} - completions_model_json['completions'] = ['testString'] - - # Construct a model instance of Completions by calling from_dict on the json representation - completions_model = Completions.from_dict(completions_model_json) - assert completions_model != False - - # Construct a model instance of Completions by calling from_dict on the json representation - completions_model_dict = Completions.from_dict(completions_model_json).__dict__ - completions_model2 = Completions(**completions_model_dict) - - # Verify the model instances are equivalent - assert completions_model == completions_model2 - - # Convert model instance back to dict and verify no loss of data - completions_model_json2 = completions_model.to_dict() - assert completions_model_json2 == completions_model_json - - -class TestModel_Configuration: - """ - Test Class for Configuration - """ - - def test_configuration_serialization(self): - """ - Test serialization/deserialization for Configuration - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - pdf_heading_detection_model = {} # PdfHeadingDetection - pdf_heading_detection_model['fonts'] = [font_setting_model] - - pdf_settings_model = {} # PdfSettings - pdf_settings_model['heading'] = pdf_heading_detection_model - - word_style_model = {} # WordStyle - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - word_heading_detection_model = {} # WordHeadingDetection - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - word_settings_model = {} # WordSettings - word_settings_model['heading'] = word_heading_detection_model - - x_path_patterns_model = {} # XPathPatterns - x_path_patterns_model['xpaths'] = ['testString'] - - html_settings_model = {} # HtmlSettings - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['span'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - segment_settings_model = {} # SegmentSettings - segment_settings_model['enabled'] = True - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['custom-field-1', 'custom-field-2'] - - normalization_operation_model = {} # NormalizationOperation - normalization_operation_model['operation'] = 'move' - normalization_operation_model['source_field'] = 'extracted_metadata.title' - normalization_operation_model['destination_field'] = 'metadata.title' - - conversions_model = {} # Conversions - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = False - nlu_enrichment_keywords_model['limit'] = 50 - - nlu_enrichment_entities_model = {} # NluEnrichmentEntities - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = False - nlu_enrichment_entities_model['limit'] = 50 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'WKS-model-id' - - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['IBM', 'Watson'] - - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['IBM', 'Watson'] - - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 50 - - nlu_enrichment_relations_model = {} # NluEnrichmentRelations - nlu_enrichment_relations_model['model'] = 'WKS-model-id' - - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts - nlu_enrichment_concepts_model['limit'] = 8 - - nlu_enrichment_features_model = {} # NluEnrichmentFeatures - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - enrichment_options_model = {} # EnrichmentOptions - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - enrichment_model = {} # Enrichment - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'enriched_title' - enrichment_model['source_field'] = 'title' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'natural_language_understanding' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - source_schedule_model = {} # SourceSchedule - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'weekly' - - source_options_folder_model = {} # SourceOptionsFolder - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - source_options_object_model = {} # SourceOptionsObject - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - source_options_site_coll_model = {} # SourceOptionsSiteColl - source_options_site_coll_model['site_collection_path'] = '/sites/TestSiteA' - source_options_site_coll_model['limit'] = 10 - - source_options_web_crawl_model = {} # SourceOptionsWebCrawl - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - source_options_buckets_model = {} # SourceOptionsBuckets - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - source_options_model = {} # SourceOptions - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - source_model = {} # Source - source_model['type'] = 'salesforce' - source_model['credential_id'] = '00ad0000-0000-11e8-ba89-0ed5f00f718b' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - # Construct a json representation of a Configuration model - configuration_model_json = {} - configuration_model_json['name'] = 'testString' - configuration_model_json['description'] = 'testString' - configuration_model_json['conversions'] = conversions_model - configuration_model_json['enrichments'] = [enrichment_model] - configuration_model_json['normalizations'] = [normalization_operation_model] - configuration_model_json['source'] = source_model - - # Construct a model instance of Configuration by calling from_dict on the json representation - configuration_model = Configuration.from_dict(configuration_model_json) - assert configuration_model != False - - # Construct a model instance of Configuration by calling from_dict on the json representation - configuration_model_dict = Configuration.from_dict(configuration_model_json).__dict__ - configuration_model2 = Configuration(**configuration_model_dict) - - # Verify the model instances are equivalent - assert configuration_model == configuration_model2 - - # Convert model instance back to dict and verify no loss of data - configuration_model_json2 = configuration_model.to_dict() - assert configuration_model_json2 == configuration_model_json - - -class TestModel_Conversions: - """ - Test Class for Conversions - """ - - def test_conversions_serialization(self): - """ - Test serialization/deserialization for Conversions - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - pdf_heading_detection_model = {} # PdfHeadingDetection - pdf_heading_detection_model['fonts'] = [font_setting_model] - - pdf_settings_model = {} # PdfSettings - pdf_settings_model['heading'] = pdf_heading_detection_model - - word_style_model = {} # WordStyle - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - word_heading_detection_model = {} # WordHeadingDetection - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - word_settings_model = {} # WordSettings - word_settings_model['heading'] = word_heading_detection_model - - x_path_patterns_model = {} # XPathPatterns - x_path_patterns_model['xpaths'] = ['testString'] - - html_settings_model = {} # HtmlSettings - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - segment_settings_model = {} # SegmentSettings - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - normalization_operation_model = {} # NormalizationOperation - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - # Construct a json representation of a Conversions model - conversions_model_json = {} - conversions_model_json['pdf'] = pdf_settings_model - conversions_model_json['word'] = word_settings_model - conversions_model_json['html'] = html_settings_model - conversions_model_json['segment'] = segment_settings_model - conversions_model_json['json_normalizations'] = [normalization_operation_model] - conversions_model_json['image_text_recognition'] = True - - # Construct a model instance of Conversions by calling from_dict on the json representation - conversions_model = Conversions.from_dict(conversions_model_json) - assert conversions_model != False - - # Construct a model instance of Conversions by calling from_dict on the json representation - conversions_model_dict = Conversions.from_dict(conversions_model_json).__dict__ - conversions_model2 = Conversions(**conversions_model_dict) - - # Verify the model instances are equivalent - assert conversions_model == conversions_model2 - - # Convert model instance back to dict and verify no loss of data - conversions_model_json2 = conversions_model.to_dict() - assert conversions_model_json2 == conversions_model_json - - -class TestModel_CreateEventResponse: - """ - Test Class for CreateEventResponse - """ - - def test_create_event_response_serialization(self): - """ - Test serialization/deserialization for CreateEventResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - event_data_model = {} # EventData - event_data_model['environment_id'] = 'testString' - event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = '2019-01-01T12:00:00Z' - event_data_model['display_rank'] = 38 - event_data_model['collection_id'] = 'testString' - event_data_model['document_id'] = 'testString' - - # Construct a json representation of a CreateEventResponse model - create_event_response_model_json = {} - create_event_response_model_json['type'] = 'click' - create_event_response_model_json['data'] = event_data_model - - # Construct a model instance of CreateEventResponse by calling from_dict on the json representation - create_event_response_model = CreateEventResponse.from_dict(create_event_response_model_json) - assert create_event_response_model != False - - # Construct a model instance of CreateEventResponse by calling from_dict on the json representation - create_event_response_model_dict = CreateEventResponse.from_dict(create_event_response_model_json).__dict__ - create_event_response_model2 = CreateEventResponse(**create_event_response_model_dict) - - # Verify the model instances are equivalent - assert create_event_response_model == create_event_response_model2 - - # Convert model instance back to dict and verify no loss of data - create_event_response_model_json2 = create_event_response_model.to_dict() - assert create_event_response_model_json2 == create_event_response_model_json - - -class TestModel_CredentialDetails: - """ - Test Class for CredentialDetails - """ - - def test_credential_details_serialization(self): - """ - Test serialization/deserialization for CredentialDetails - """ - - # Construct a json representation of a CredentialDetails model - credential_details_model_json = {} - credential_details_model_json['credential_type'] = 'oauth2' - credential_details_model_json['client_id'] = 'testString' - credential_details_model_json['enterprise_id'] = 'testString' - credential_details_model_json['url'] = 'testString' - credential_details_model_json['username'] = 'testString' - credential_details_model_json['organization_url'] = 'testString' - credential_details_model_json['site_collection.path'] = 'testString' - credential_details_model_json['client_secret'] = 'testString' - credential_details_model_json['public_key_id'] = 'testString' - credential_details_model_json['private_key'] = 'testString' - credential_details_model_json['passphrase'] = 'testString' - credential_details_model_json['password'] = 'testString' - credential_details_model_json['gateway_id'] = 'testString' - credential_details_model_json['source_version'] = 'online' - credential_details_model_json['web_application_url'] = 'testString' - credential_details_model_json['domain'] = 'testString' - credential_details_model_json['endpoint'] = 'testString' - credential_details_model_json['access_key_id'] = 'testString' - credential_details_model_json['secret_access_key'] = 'testString' - - # Construct a model instance of CredentialDetails by calling from_dict on the json representation - credential_details_model = CredentialDetails.from_dict(credential_details_model_json) - assert credential_details_model != False - - # Construct a model instance of CredentialDetails by calling from_dict on the json representation - credential_details_model_dict = CredentialDetails.from_dict(credential_details_model_json).__dict__ - credential_details_model2 = CredentialDetails(**credential_details_model_dict) - - # Verify the model instances are equivalent - assert credential_details_model == credential_details_model2 - - # Convert model instance back to dict and verify no loss of data - credential_details_model_json2 = credential_details_model.to_dict() - assert credential_details_model_json2 == credential_details_model_json - - -class TestModel_Credentials: - """ - Test Class for Credentials - """ - - def test_credentials_serialization(self): - """ - Test serialization/deserialization for Credentials - """ - - # Construct dict forms of any model objects needed in order to build this model. - - credential_details_model = {} # CredentialDetails - credential_details_model['credential_type'] = 'username_password' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'login.salesforce.com' - credential_details_model['username'] = 'user@email.address' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - status_details_model = {} # StatusDetails - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - # Construct a json representation of a Credentials model - credentials_model_json = {} - credentials_model_json['source_type'] = 'box' - credentials_model_json['credential_details'] = credential_details_model - credentials_model_json['status'] = status_details_model - - # Construct a model instance of Credentials by calling from_dict on the json representation - credentials_model = Credentials.from_dict(credentials_model_json) - assert credentials_model != False - - # Construct a model instance of Credentials by calling from_dict on the json representation - credentials_model_dict = Credentials.from_dict(credentials_model_json).__dict__ - credentials_model2 = Credentials(**credentials_model_dict) - - # Verify the model instances are equivalent - assert credentials_model == credentials_model2 - - # Convert model instance back to dict and verify no loss of data - credentials_model_json2 = credentials_model.to_dict() - assert credentials_model_json2 == credentials_model_json - - -class TestModel_CredentialsList: - """ - Test Class for CredentialsList - """ - - def test_credentials_list_serialization(self): - """ - Test serialization/deserialization for CredentialsList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - credential_details_model = {} # CredentialDetails - credential_details_model['credential_type'] = 'username_password' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'login.salesforce.com' - credential_details_model['username'] = 'user@email.address' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - status_details_model = {} # StatusDetails - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - credentials_model = {} # Credentials - credentials_model['source_type'] = 'salesforce' - credentials_model['credential_details'] = credential_details_model - credentials_model['status'] = status_details_model - - # Construct a json representation of a CredentialsList model - credentials_list_model_json = {} - credentials_list_model_json['credentials'] = [credentials_model] - - # Construct a model instance of CredentialsList by calling from_dict on the json representation - credentials_list_model = CredentialsList.from_dict(credentials_list_model_json) - assert credentials_list_model != False - - # Construct a model instance of CredentialsList by calling from_dict on the json representation - credentials_list_model_dict = CredentialsList.from_dict(credentials_list_model_json).__dict__ - credentials_list_model2 = CredentialsList(**credentials_list_model_dict) - - # Verify the model instances are equivalent - assert credentials_list_model == credentials_list_model2 - - # Convert model instance back to dict and verify no loss of data - credentials_list_model_json2 = credentials_list_model.to_dict() - assert credentials_list_model_json2 == credentials_list_model_json - - -class TestModel_DeleteCollectionResponse: - """ - Test Class for DeleteCollectionResponse - """ - - def test_delete_collection_response_serialization(self): - """ - Test serialization/deserialization for DeleteCollectionResponse - """ - - # Construct a json representation of a DeleteCollectionResponse model - delete_collection_response_model_json = {} - delete_collection_response_model_json['collection_id'] = 'testString' - delete_collection_response_model_json['status'] = 'deleted' - - # Construct a model instance of DeleteCollectionResponse by calling from_dict on the json representation - delete_collection_response_model = DeleteCollectionResponse.from_dict(delete_collection_response_model_json) - assert delete_collection_response_model != False - - # Construct a model instance of DeleteCollectionResponse by calling from_dict on the json representation - delete_collection_response_model_dict = DeleteCollectionResponse.from_dict(delete_collection_response_model_json).__dict__ - delete_collection_response_model2 = DeleteCollectionResponse(**delete_collection_response_model_dict) - - # Verify the model instances are equivalent - assert delete_collection_response_model == delete_collection_response_model2 - - # Convert model instance back to dict and verify no loss of data - delete_collection_response_model_json2 = delete_collection_response_model.to_dict() - assert delete_collection_response_model_json2 == delete_collection_response_model_json - - -class TestModel_DeleteConfigurationResponse: - """ - Test Class for DeleteConfigurationResponse - """ - - def test_delete_configuration_response_serialization(self): - """ - Test serialization/deserialization for DeleteConfigurationResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - - # Construct a json representation of a DeleteConfigurationResponse model - delete_configuration_response_model_json = {} - delete_configuration_response_model_json['configuration_id'] = 'testString' - delete_configuration_response_model_json['status'] = 'deleted' - delete_configuration_response_model_json['notices'] = [notice_model] - - # Construct a model instance of DeleteConfigurationResponse by calling from_dict on the json representation - delete_configuration_response_model = DeleteConfigurationResponse.from_dict(delete_configuration_response_model_json) - assert delete_configuration_response_model != False - - # Construct a model instance of DeleteConfigurationResponse by calling from_dict on the json representation - delete_configuration_response_model_dict = DeleteConfigurationResponse.from_dict(delete_configuration_response_model_json).__dict__ - delete_configuration_response_model2 = DeleteConfigurationResponse(**delete_configuration_response_model_dict) - - # Verify the model instances are equivalent - assert delete_configuration_response_model == delete_configuration_response_model2 - - # Convert model instance back to dict and verify no loss of data - delete_configuration_response_model_json2 = delete_configuration_response_model.to_dict() - assert delete_configuration_response_model_json2 == delete_configuration_response_model_json - - -class TestModel_DeleteCredentials: - """ - Test Class for DeleteCredentials - """ - - def test_delete_credentials_serialization(self): - """ - Test serialization/deserialization for DeleteCredentials - """ - - # Construct a json representation of a DeleteCredentials model - delete_credentials_model_json = {} - delete_credentials_model_json['credential_id'] = 'testString' - delete_credentials_model_json['status'] = 'deleted' - - # Construct a model instance of DeleteCredentials by calling from_dict on the json representation - delete_credentials_model = DeleteCredentials.from_dict(delete_credentials_model_json) - assert delete_credentials_model != False - - # Construct a model instance of DeleteCredentials by calling from_dict on the json representation - delete_credentials_model_dict = DeleteCredentials.from_dict(delete_credentials_model_json).__dict__ - delete_credentials_model2 = DeleteCredentials(**delete_credentials_model_dict) - - # Verify the model instances are equivalent - assert delete_credentials_model == delete_credentials_model2 - - # Convert model instance back to dict and verify no loss of data - delete_credentials_model_json2 = delete_credentials_model.to_dict() - assert delete_credentials_model_json2 == delete_credentials_model_json - - -class TestModel_DeleteDocumentResponse: - """ - Test Class for DeleteDocumentResponse - """ - - def test_delete_document_response_serialization(self): - """ - Test serialization/deserialization for DeleteDocumentResponse - """ - - # Construct a json representation of a DeleteDocumentResponse model - delete_document_response_model_json = {} - delete_document_response_model_json['document_id'] = 'testString' - delete_document_response_model_json['status'] = 'deleted' - - # Construct a model instance of DeleteDocumentResponse by calling from_dict on the json representation - delete_document_response_model = DeleteDocumentResponse.from_dict(delete_document_response_model_json) - assert delete_document_response_model != False - - # Construct a model instance of DeleteDocumentResponse by calling from_dict on the json representation - delete_document_response_model_dict = DeleteDocumentResponse.from_dict(delete_document_response_model_json).__dict__ - delete_document_response_model2 = DeleteDocumentResponse(**delete_document_response_model_dict) - - # Verify the model instances are equivalent - assert delete_document_response_model == delete_document_response_model2 - - # Convert model instance back to dict and verify no loss of data - delete_document_response_model_json2 = delete_document_response_model.to_dict() - assert delete_document_response_model_json2 == delete_document_response_model_json - - -class TestModel_DeleteEnvironmentResponse: - """ - Test Class for DeleteEnvironmentResponse - """ - - def test_delete_environment_response_serialization(self): - """ - Test serialization/deserialization for DeleteEnvironmentResponse - """ - - # Construct a json representation of a DeleteEnvironmentResponse model - delete_environment_response_model_json = {} - delete_environment_response_model_json['environment_id'] = 'testString' - delete_environment_response_model_json['status'] = 'deleted' - - # Construct a model instance of DeleteEnvironmentResponse by calling from_dict on the json representation - delete_environment_response_model = DeleteEnvironmentResponse.from_dict(delete_environment_response_model_json) - assert delete_environment_response_model != False - - # Construct a model instance of DeleteEnvironmentResponse by calling from_dict on the json representation - delete_environment_response_model_dict = DeleteEnvironmentResponse.from_dict(delete_environment_response_model_json).__dict__ - delete_environment_response_model2 = DeleteEnvironmentResponse(**delete_environment_response_model_dict) - - # Verify the model instances are equivalent - assert delete_environment_response_model == delete_environment_response_model2 - - # Convert model instance back to dict and verify no loss of data - delete_environment_response_model_json2 = delete_environment_response_model.to_dict() - assert delete_environment_response_model_json2 == delete_environment_response_model_json - - -class TestModel_DiskUsage: - """ - Test Class for DiskUsage - """ - - def test_disk_usage_serialization(self): - """ - Test serialization/deserialization for DiskUsage - """ - - # Construct a json representation of a DiskUsage model - disk_usage_model_json = {} - - # Construct a model instance of DiskUsage by calling from_dict on the json representation - disk_usage_model = DiskUsage.from_dict(disk_usage_model_json) - assert disk_usage_model != False - - # Construct a model instance of DiskUsage by calling from_dict on the json representation - disk_usage_model_dict = DiskUsage.from_dict(disk_usage_model_json).__dict__ - disk_usage_model2 = DiskUsage(**disk_usage_model_dict) - - # Verify the model instances are equivalent - assert disk_usage_model == disk_usage_model2 - - # Convert model instance back to dict and verify no loss of data - disk_usage_model_json2 = disk_usage_model.to_dict() - assert disk_usage_model_json2 == disk_usage_model_json - - -class TestModel_DocumentAccepted: - """ - Test Class for DocumentAccepted - """ - - def test_document_accepted_serialization(self): - """ - Test serialization/deserialization for DocumentAccepted - """ - - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - - # Construct a json representation of a DocumentAccepted model - document_accepted_model_json = {} - document_accepted_model_json['document_id'] = 'testString' - document_accepted_model_json['status'] = 'processing' - document_accepted_model_json['notices'] = [notice_model] - - # Construct a model instance of DocumentAccepted by calling from_dict on the json representation - document_accepted_model = DocumentAccepted.from_dict(document_accepted_model_json) - assert document_accepted_model != False - - # Construct a model instance of DocumentAccepted by calling from_dict on the json representation - document_accepted_model_dict = DocumentAccepted.from_dict(document_accepted_model_json).__dict__ - document_accepted_model2 = DocumentAccepted(**document_accepted_model_dict) - - # Verify the model instances are equivalent - assert document_accepted_model == document_accepted_model2 - - # Convert model instance back to dict and verify no loss of data - document_accepted_model_json2 = document_accepted_model.to_dict() - assert document_accepted_model_json2 == document_accepted_model_json - - -class TestModel_DocumentCounts: - """ - Test Class for DocumentCounts - """ - - def test_document_counts_serialization(self): - """ - Test serialization/deserialization for DocumentCounts - """ - - # Construct a json representation of a DocumentCounts model - document_counts_model_json = {} - - # Construct a model instance of DocumentCounts by calling from_dict on the json representation - document_counts_model = DocumentCounts.from_dict(document_counts_model_json) - assert document_counts_model != False - - # Construct a model instance of DocumentCounts by calling from_dict on the json representation - document_counts_model_dict = DocumentCounts.from_dict(document_counts_model_json).__dict__ - document_counts_model2 = DocumentCounts(**document_counts_model_dict) - - # Verify the model instances are equivalent - assert document_counts_model == document_counts_model2 - - # Convert model instance back to dict and verify no loss of data - document_counts_model_json2 = document_counts_model.to_dict() - assert document_counts_model_json2 == document_counts_model_json - - -class TestModel_DocumentStatus: - """ - Test Class for DocumentStatus - """ - - def test_document_status_serialization(self): - """ - Test serialization/deserialization for DocumentStatus - """ - - # Construct a json representation of a DocumentStatus model - document_status_model_json = {} - document_status_model_json['filename'] = 'testString' - document_status_model_json['file_type'] = 'pdf' - document_status_model_json['sha1'] = 'testString' - - # Construct a model instance of DocumentStatus by calling from_dict on the json representation - document_status_model = DocumentStatus.from_dict(document_status_model_json) - assert document_status_model != False - - # Construct a model instance of DocumentStatus by calling from_dict on the json representation - document_status_model_dict = DocumentStatus.from_dict(document_status_model_json).__dict__ - document_status_model2 = DocumentStatus(**document_status_model_dict) - - # Verify the model instances are equivalent - assert document_status_model == document_status_model2 - - # Convert model instance back to dict and verify no loss of data - document_status_model_json2 = document_status_model.to_dict() - assert document_status_model_json2 == document_status_model_json - - -class TestModel_Enrichment: - """ - Test Class for Enrichment - """ - - def test_enrichment_serialization(self): - """ - Test serialization/deserialization for Enrichment - """ - - # Construct dict forms of any model objects needed in order to build this model. - - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - nlu_enrichment_entities_model = {} # NluEnrichmentEntities - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - nlu_enrichment_relations_model = {} # NluEnrichmentRelations - nlu_enrichment_relations_model['model'] = 'testString' - - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts - nlu_enrichment_concepts_model['limit'] = 38 - - nlu_enrichment_features_model = {} # NluEnrichmentFeatures - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - enrichment_options_model = {} # EnrichmentOptions - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - # Construct a json representation of a Enrichment model - enrichment_model_json = {} - enrichment_model_json['description'] = 'testString' - enrichment_model_json['destination_field'] = 'testString' - enrichment_model_json['source_field'] = 'testString' - enrichment_model_json['overwrite'] = False - enrichment_model_json['enrichment'] = 'testString' - enrichment_model_json['ignore_downstream_errors'] = False - enrichment_model_json['options'] = enrichment_options_model - - # Construct a model instance of Enrichment by calling from_dict on the json representation - enrichment_model = Enrichment.from_dict(enrichment_model_json) - assert enrichment_model != False - - # Construct a model instance of Enrichment by calling from_dict on the json representation - enrichment_model_dict = Enrichment.from_dict(enrichment_model_json).__dict__ - enrichment_model2 = Enrichment(**enrichment_model_dict) - - # Verify the model instances are equivalent - assert enrichment_model == enrichment_model2 - - # Convert model instance back to dict and verify no loss of data - enrichment_model_json2 = enrichment_model.to_dict() - assert enrichment_model_json2 == enrichment_model_json - - -class TestModel_EnrichmentOptions: - """ - Test Class for EnrichmentOptions - """ - - def test_enrichment_options_serialization(self): - """ - Test serialization/deserialization for EnrichmentOptions - """ - - # Construct dict forms of any model objects needed in order to build this model. - - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - nlu_enrichment_entities_model = {} # NluEnrichmentEntities - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - nlu_enrichment_relations_model = {} # NluEnrichmentRelations - nlu_enrichment_relations_model['model'] = 'testString' - - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts - nlu_enrichment_concepts_model['limit'] = 38 - - nlu_enrichment_features_model = {} # NluEnrichmentFeatures - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - # Construct a json representation of a EnrichmentOptions model - enrichment_options_model_json = {} - enrichment_options_model_json['features'] = nlu_enrichment_features_model - enrichment_options_model_json['language'] = 'ar' - enrichment_options_model_json['model'] = 'testString' - - # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation - enrichment_options_model = EnrichmentOptions.from_dict(enrichment_options_model_json) - assert enrichment_options_model != False - - # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation - enrichment_options_model_dict = EnrichmentOptions.from_dict(enrichment_options_model_json).__dict__ - enrichment_options_model2 = EnrichmentOptions(**enrichment_options_model_dict) - - # Verify the model instances are equivalent - assert enrichment_options_model == enrichment_options_model2 - - # Convert model instance back to dict and verify no loss of data - enrichment_options_model_json2 = enrichment_options_model.to_dict() - assert enrichment_options_model_json2 == enrichment_options_model_json - - -class TestModel_Environment: - """ - Test Class for Environment - """ - - def test_environment_serialization(self): - """ - Test serialization/deserialization for Environment - """ - - # Construct dict forms of any model objects needed in order to build this model. - - environment_documents_model = {} # EnvironmentDocuments - - disk_usage_model = {} # DiskUsage - - collection_usage_model = {} # CollectionUsage - - index_capacity_model = {} # IndexCapacity - index_capacity_model['documents'] = environment_documents_model - index_capacity_model['disk_usage'] = disk_usage_model - index_capacity_model['collections'] = collection_usage_model - - search_status_model = {} # SearchStatus - search_status_model['scope'] = 'testString' - search_status_model['status'] = 'NO_DATA' - search_status_model['status_description'] = 'testString' - search_status_model['last_trained'] = '2019-01-01' - - # Construct a json representation of a Environment model - environment_model_json = {} - environment_model_json['name'] = 'testString' - environment_model_json['description'] = 'testString' - environment_model_json['size'] = 'LT' - environment_model_json['requested_size'] = 'testString' - environment_model_json['index_capacity'] = index_capacity_model - environment_model_json['search_status'] = search_status_model - - # Construct a model instance of Environment by calling from_dict on the json representation - environment_model = Environment.from_dict(environment_model_json) - assert environment_model != False - - # Construct a model instance of Environment by calling from_dict on the json representation - environment_model_dict = Environment.from_dict(environment_model_json).__dict__ - environment_model2 = Environment(**environment_model_dict) - - # Verify the model instances are equivalent - assert environment_model == environment_model2 - - # Convert model instance back to dict and verify no loss of data - environment_model_json2 = environment_model.to_dict() - assert environment_model_json2 == environment_model_json - - -class TestModel_EnvironmentDocuments: - """ - Test Class for EnvironmentDocuments - """ - - def test_environment_documents_serialization(self): - """ - Test serialization/deserialization for EnvironmentDocuments - """ - - # Construct a json representation of a EnvironmentDocuments model - environment_documents_model_json = {} - - # Construct a model instance of EnvironmentDocuments by calling from_dict on the json representation - environment_documents_model = EnvironmentDocuments.from_dict(environment_documents_model_json) - assert environment_documents_model != False - - # Construct a model instance of EnvironmentDocuments by calling from_dict on the json representation - environment_documents_model_dict = EnvironmentDocuments.from_dict(environment_documents_model_json).__dict__ - environment_documents_model2 = EnvironmentDocuments(**environment_documents_model_dict) - - # Verify the model instances are equivalent - assert environment_documents_model == environment_documents_model2 - - # Convert model instance back to dict and verify no loss of data - environment_documents_model_json2 = environment_documents_model.to_dict() - assert environment_documents_model_json2 == environment_documents_model_json - - -class TestModel_EventData: - """ - Test Class for EventData - """ - - def test_event_data_serialization(self): - """ - Test serialization/deserialization for EventData - """ - - # Construct a json representation of a EventData model - event_data_model_json = {} - event_data_model_json['environment_id'] = 'testString' - event_data_model_json['session_token'] = 'testString' - event_data_model_json['client_timestamp'] = '2019-01-01T12:00:00Z' - event_data_model_json['display_rank'] = 38 - event_data_model_json['collection_id'] = 'testString' - event_data_model_json['document_id'] = 'testString' - - # Construct a model instance of EventData by calling from_dict on the json representation - event_data_model = EventData.from_dict(event_data_model_json) - assert event_data_model != False - - # Construct a model instance of EventData by calling from_dict on the json representation - event_data_model_dict = EventData.from_dict(event_data_model_json).__dict__ - event_data_model2 = EventData(**event_data_model_dict) - - # Verify the model instances are equivalent - assert event_data_model == event_data_model2 - - # Convert model instance back to dict and verify no loss of data - event_data_model_json2 = event_data_model.to_dict() - assert event_data_model_json2 == event_data_model_json - - -class TestModel_Expansion: - """ - Test Class for Expansion - """ - - def test_expansion_serialization(self): - """ - Test serialization/deserialization for Expansion - """ - - # Construct a json representation of a Expansion model - expansion_model_json = {} - expansion_model_json['input_terms'] = ['testString'] - expansion_model_json['expanded_terms'] = ['testString'] - - # Construct a model instance of Expansion by calling from_dict on the json representation - expansion_model = Expansion.from_dict(expansion_model_json) - assert expansion_model != False - - # Construct a model instance of Expansion by calling from_dict on the json representation - expansion_model_dict = Expansion.from_dict(expansion_model_json).__dict__ - expansion_model2 = Expansion(**expansion_model_dict) - - # Verify the model instances are equivalent - assert expansion_model == expansion_model2 - - # Convert model instance back to dict and verify no loss of data - expansion_model_json2 = expansion_model.to_dict() - assert expansion_model_json2 == expansion_model_json - - -class TestModel_Expansions: - """ - Test Class for Expansions - """ - - def test_expansions_serialization(self): - """ - Test serialization/deserialization for Expansions - """ - - # Construct dict forms of any model objects needed in order to build this model. - - expansion_model = {} # Expansion - expansion_model['input_terms'] = ['testString'] - expansion_model['expanded_terms'] = ['testString'] - - # Construct a json representation of a Expansions model - expansions_model_json = {} - expansions_model_json['expansions'] = [expansion_model] - - # Construct a model instance of Expansions by calling from_dict on the json representation - expansions_model = Expansions.from_dict(expansions_model_json) - assert expansions_model != False - - # Construct a model instance of Expansions by calling from_dict on the json representation - expansions_model_dict = Expansions.from_dict(expansions_model_json).__dict__ - expansions_model2 = Expansions(**expansions_model_dict) - - # Verify the model instances are equivalent - assert expansions_model == expansions_model2 - - # Convert model instance back to dict and verify no loss of data - expansions_model_json2 = expansions_model.to_dict() - assert expansions_model_json2 == expansions_model_json - - -class TestModel_Field: - """ - Test Class for Field - """ - - def test_field_serialization(self): - """ - Test serialization/deserialization for Field - """ - - # Construct a json representation of a Field model - field_model_json = {} - - # Construct a model instance of Field by calling from_dict on the json representation - field_model = Field.from_dict(field_model_json) - assert field_model != False - - # Construct a model instance of Field by calling from_dict on the json representation - field_model_dict = Field.from_dict(field_model_json).__dict__ - field_model2 = Field(**field_model_dict) - - # Verify the model instances are equivalent - assert field_model == field_model2 - - # Convert model instance back to dict and verify no loss of data - field_model_json2 = field_model.to_dict() - assert field_model_json2 == field_model_json - - -class TestModel_FontSetting: - """ - Test Class for FontSetting - """ - - def test_font_setting_serialization(self): - """ - Test serialization/deserialization for FontSetting - """ - - # Construct a json representation of a FontSetting model - font_setting_model_json = {} - font_setting_model_json['level'] = 38 - font_setting_model_json['min_size'] = 38 - font_setting_model_json['max_size'] = 38 - font_setting_model_json['bold'] = True - font_setting_model_json['italic'] = True - font_setting_model_json['name'] = 'testString' - - # Construct a model instance of FontSetting by calling from_dict on the json representation - font_setting_model = FontSetting.from_dict(font_setting_model_json) - assert font_setting_model != False - - # Construct a model instance of FontSetting by calling from_dict on the json representation - font_setting_model_dict = FontSetting.from_dict(font_setting_model_json).__dict__ - font_setting_model2 = FontSetting(**font_setting_model_dict) - - # Verify the model instances are equivalent - assert font_setting_model == font_setting_model2 - - # Convert model instance back to dict and verify no loss of data - font_setting_model_json2 = font_setting_model.to_dict() - assert font_setting_model_json2 == font_setting_model_json - - -class TestModel_Gateway: - """ - Test Class for Gateway - """ - - def test_gateway_serialization(self): - """ - Test serialization/deserialization for Gateway - """ - - # Construct a json representation of a Gateway model - gateway_model_json = {} - gateway_model_json['gateway_id'] = 'testString' - gateway_model_json['name'] = 'testString' - gateway_model_json['status'] = 'connected' - gateway_model_json['token'] = 'testString' - gateway_model_json['token_id'] = 'testString' - - # Construct a model instance of Gateway by calling from_dict on the json representation - gateway_model = Gateway.from_dict(gateway_model_json) - assert gateway_model != False - - # Construct a model instance of Gateway by calling from_dict on the json representation - gateway_model_dict = Gateway.from_dict(gateway_model_json).__dict__ - gateway_model2 = Gateway(**gateway_model_dict) - - # Verify the model instances are equivalent - assert gateway_model == gateway_model2 - - # Convert model instance back to dict and verify no loss of data - gateway_model_json2 = gateway_model.to_dict() - assert gateway_model_json2 == gateway_model_json - - -class TestModel_GatewayDelete: - """ - Test Class for GatewayDelete - """ - - def test_gateway_delete_serialization(self): - """ - Test serialization/deserialization for GatewayDelete - """ - - # Construct a json representation of a GatewayDelete model - gateway_delete_model_json = {} - gateway_delete_model_json['gateway_id'] = 'testString' - gateway_delete_model_json['status'] = 'testString' - - # Construct a model instance of GatewayDelete by calling from_dict on the json representation - gateway_delete_model = GatewayDelete.from_dict(gateway_delete_model_json) - assert gateway_delete_model != False - - # Construct a model instance of GatewayDelete by calling from_dict on the json representation - gateway_delete_model_dict = GatewayDelete.from_dict(gateway_delete_model_json).__dict__ - gateway_delete_model2 = GatewayDelete(**gateway_delete_model_dict) - - # Verify the model instances are equivalent - assert gateway_delete_model == gateway_delete_model2 - - # Convert model instance back to dict and verify no loss of data - gateway_delete_model_json2 = gateway_delete_model.to_dict() - assert gateway_delete_model_json2 == gateway_delete_model_json - - -class TestModel_GatewayList: - """ - Test Class for GatewayList - """ - - def test_gateway_list_serialization(self): - """ - Test serialization/deserialization for GatewayList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - gateway_model = {} # Gateway - gateway_model['gateway_id'] = 'testString' - gateway_model['name'] = 'testString' - gateway_model['status'] = 'connected' - gateway_model['token'] = 'testString' - gateway_model['token_id'] = 'testString' - - # Construct a json representation of a GatewayList model - gateway_list_model_json = {} - gateway_list_model_json['gateways'] = [gateway_model] - - # Construct a model instance of GatewayList by calling from_dict on the json representation - gateway_list_model = GatewayList.from_dict(gateway_list_model_json) - assert gateway_list_model != False - - # Construct a model instance of GatewayList by calling from_dict on the json representation - gateway_list_model_dict = GatewayList.from_dict(gateway_list_model_json).__dict__ - gateway_list_model2 = GatewayList(**gateway_list_model_dict) - - # Verify the model instances are equivalent - assert gateway_list_model == gateway_list_model2 - - # Convert model instance back to dict and verify no loss of data - gateway_list_model_json2 = gateway_list_model.to_dict() - assert gateway_list_model_json2 == gateway_list_model_json - - -class TestModel_HtmlSettings: - """ - Test Class for HtmlSettings - """ - - def test_html_settings_serialization(self): - """ - Test serialization/deserialization for HtmlSettings - """ - - # Construct dict forms of any model objects needed in order to build this model. - - x_path_patterns_model = {} # XPathPatterns - x_path_patterns_model['xpaths'] = ['testString'] - - # Construct a json representation of a HtmlSettings model - html_settings_model_json = {} - html_settings_model_json['exclude_tags_completely'] = ['testString'] - html_settings_model_json['exclude_tags_keep_content'] = ['testString'] - html_settings_model_json['keep_content'] = x_path_patterns_model - html_settings_model_json['exclude_content'] = x_path_patterns_model - html_settings_model_json['keep_tag_attributes'] = ['testString'] - html_settings_model_json['exclude_tag_attributes'] = ['testString'] - - # Construct a model instance of HtmlSettings by calling from_dict on the json representation - html_settings_model = HtmlSettings.from_dict(html_settings_model_json) - assert html_settings_model != False - - # Construct a model instance of HtmlSettings by calling from_dict on the json representation - html_settings_model_dict = HtmlSettings.from_dict(html_settings_model_json).__dict__ - html_settings_model2 = HtmlSettings(**html_settings_model_dict) - - # Verify the model instances are equivalent - assert html_settings_model == html_settings_model2 - - # Convert model instance back to dict and verify no loss of data - html_settings_model_json2 = html_settings_model.to_dict() - assert html_settings_model_json2 == html_settings_model_json - - -class TestModel_IndexCapacity: - """ - Test Class for IndexCapacity - """ - - def test_index_capacity_serialization(self): - """ - Test serialization/deserialization for IndexCapacity - """ - - # Construct dict forms of any model objects needed in order to build this model. - - environment_documents_model = {} # EnvironmentDocuments - - disk_usage_model = {} # DiskUsage - - collection_usage_model = {} # CollectionUsage - - # Construct a json representation of a IndexCapacity model - index_capacity_model_json = {} - index_capacity_model_json['documents'] = environment_documents_model - index_capacity_model_json['disk_usage'] = disk_usage_model - index_capacity_model_json['collections'] = collection_usage_model - - # Construct a model instance of IndexCapacity by calling from_dict on the json representation - index_capacity_model = IndexCapacity.from_dict(index_capacity_model_json) - assert index_capacity_model != False - - # Construct a model instance of IndexCapacity by calling from_dict on the json representation - index_capacity_model_dict = IndexCapacity.from_dict(index_capacity_model_json).__dict__ - index_capacity_model2 = IndexCapacity(**index_capacity_model_dict) - - # Verify the model instances are equivalent - assert index_capacity_model == index_capacity_model2 - - # Convert model instance back to dict and verify no loss of data - index_capacity_model_json2 = index_capacity_model.to_dict() - assert index_capacity_model_json2 == index_capacity_model_json - - -class TestModel_ListCollectionFieldsResponse: - """ - Test Class for ListCollectionFieldsResponse - """ - - def test_list_collection_fields_response_serialization(self): - """ - Test serialization/deserialization for ListCollectionFieldsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - field_model = {} # Field - - # Construct a json representation of a ListCollectionFieldsResponse model - list_collection_fields_response_model_json = {} - list_collection_fields_response_model_json['fields'] = [field_model] - - # Construct a model instance of ListCollectionFieldsResponse by calling from_dict on the json representation - list_collection_fields_response_model = ListCollectionFieldsResponse.from_dict(list_collection_fields_response_model_json) - assert list_collection_fields_response_model != False - - # Construct a model instance of ListCollectionFieldsResponse by calling from_dict on the json representation - list_collection_fields_response_model_dict = ListCollectionFieldsResponse.from_dict(list_collection_fields_response_model_json).__dict__ - list_collection_fields_response_model2 = ListCollectionFieldsResponse(**list_collection_fields_response_model_dict) - - # Verify the model instances are equivalent - assert list_collection_fields_response_model == list_collection_fields_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_collection_fields_response_model_json2 = list_collection_fields_response_model.to_dict() - assert list_collection_fields_response_model_json2 == list_collection_fields_response_model_json - - -class TestModel_ListCollectionsResponse: - """ - Test Class for ListCollectionsResponse - """ - - def test_list_collections_response_serialization(self): - """ - Test serialization/deserialization for ListCollectionsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - document_counts_model = {} # DocumentCounts - - collection_disk_usage_model = {} # CollectionDiskUsage - - training_status_model = {} # TrainingStatus - training_status_model['total_examples'] = 38 - training_status_model['available'] = True - training_status_model['processing'] = True - training_status_model['minimum_queries_added'] = True - training_status_model['minimum_examples_added'] = True - training_status_model['sufficient_label_diversity'] = True - training_status_model['notices'] = 38 - training_status_model['successfully_trained'] = '2019-01-01T12:00:00Z' - training_status_model['data_updated'] = '2019-01-01T12:00:00Z' - - source_status_model = {} # SourceStatus - source_status_model['status'] = 'running' - source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' - - collection_crawl_status_model = {} # CollectionCrawlStatus - collection_crawl_status_model['source_crawl'] = source_status_model - - sdu_status_custom_fields_model = {} # SduStatusCustomFields - sdu_status_custom_fields_model['defined'] = 26 - sdu_status_custom_fields_model['maximum_allowed'] = 26 - - sdu_status_model = {} # SduStatus - sdu_status_model['enabled'] = True - sdu_status_model['total_annotated_pages'] = 26 - sdu_status_model['total_pages'] = 26 - sdu_status_model['total_documents'] = 26 - sdu_status_model['custom_fields'] = sdu_status_custom_fields_model - - collection_model = {} # Collection - collection_model['name'] = 'example' - collection_model['description'] = 'this is a demo collection' - collection_model['configuration_id'] = '6963be41-2dea-4f79-8f52-127c63c479b0' - collection_model['language'] = 'en' - collection_model['document_counts'] = document_counts_model - collection_model['disk_usage'] = collection_disk_usage_model - collection_model['training_status'] = training_status_model - collection_model['crawl_status'] = collection_crawl_status_model - collection_model['smart_document_understanding'] = sdu_status_model - - # Construct a json representation of a ListCollectionsResponse model - list_collections_response_model_json = {} - list_collections_response_model_json['collections'] = [collection_model] - - # Construct a model instance of ListCollectionsResponse by calling from_dict on the json representation - list_collections_response_model = ListCollectionsResponse.from_dict(list_collections_response_model_json) - assert list_collections_response_model != False - - # Construct a model instance of ListCollectionsResponse by calling from_dict on the json representation - list_collections_response_model_dict = ListCollectionsResponse.from_dict(list_collections_response_model_json).__dict__ - list_collections_response_model2 = ListCollectionsResponse(**list_collections_response_model_dict) - - # Verify the model instances are equivalent - assert list_collections_response_model == list_collections_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_collections_response_model_json2 = list_collections_response_model.to_dict() - assert list_collections_response_model_json2 == list_collections_response_model_json - - -class TestModel_ListConfigurationsResponse: - """ - Test Class for ListConfigurationsResponse - """ - - def test_list_configurations_response_serialization(self): - """ - Test serialization/deserialization for ListConfigurationsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - pdf_heading_detection_model = {} # PdfHeadingDetection - pdf_heading_detection_model['fonts'] = [font_setting_model] - - pdf_settings_model = {} # PdfSettings - pdf_settings_model['heading'] = pdf_heading_detection_model - - word_style_model = {} # WordStyle - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - word_heading_detection_model = {} # WordHeadingDetection - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - word_settings_model = {} # WordSettings - word_settings_model['heading'] = word_heading_detection_model - - x_path_patterns_model = {} # XPathPatterns - x_path_patterns_model['xpaths'] = ['testString'] - - html_settings_model = {} # HtmlSettings - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - segment_settings_model = {} # SegmentSettings - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - normalization_operation_model = {} # NormalizationOperation - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - conversions_model = {} # Conversions - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - nlu_enrichment_entities_model = {} # NluEnrichmentEntities - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - nlu_enrichment_relations_model = {} # NluEnrichmentRelations - nlu_enrichment_relations_model['model'] = 'testString' - - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts - nlu_enrichment_concepts_model['limit'] = 38 - - nlu_enrichment_features_model = {} # NluEnrichmentFeatures - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - enrichment_options_model = {} # EnrichmentOptions - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - enrichment_model = {} # Enrichment - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'testString' - enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - source_schedule_model = {} # SourceSchedule - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - source_options_folder_model = {} # SourceOptionsFolder - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - source_options_object_model = {} # SourceOptionsObject - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - source_options_site_coll_model = {} # SourceOptionsSiteColl - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - source_options_web_crawl_model = {} # SourceOptionsWebCrawl - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - source_options_buckets_model = {} # SourceOptionsBuckets - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - source_options_model = {} # SourceOptions - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - source_model = {} # Source - source_model['type'] = 'box' - source_model['credential_id'] = 'testString' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - configuration_model = {} # Configuration - configuration_model['name'] = 'testString' - configuration_model['description'] = 'testString' - configuration_model['conversions'] = conversions_model - configuration_model['enrichments'] = [enrichment_model] - configuration_model['normalizations'] = [normalization_operation_model] - configuration_model['source'] = source_model - - # Construct a json representation of a ListConfigurationsResponse model - list_configurations_response_model_json = {} - list_configurations_response_model_json['configurations'] = [configuration_model] - - # Construct a model instance of ListConfigurationsResponse by calling from_dict on the json representation - list_configurations_response_model = ListConfigurationsResponse.from_dict(list_configurations_response_model_json) - assert list_configurations_response_model != False - - # Construct a model instance of ListConfigurationsResponse by calling from_dict on the json representation - list_configurations_response_model_dict = ListConfigurationsResponse.from_dict(list_configurations_response_model_json).__dict__ - list_configurations_response_model2 = ListConfigurationsResponse(**list_configurations_response_model_dict) - - # Verify the model instances are equivalent - assert list_configurations_response_model == list_configurations_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_configurations_response_model_json2 = list_configurations_response_model.to_dict() - assert list_configurations_response_model_json2 == list_configurations_response_model_json - - -class TestModel_ListEnvironmentsResponse: - """ - Test Class for ListEnvironmentsResponse - """ - - def test_list_environments_response_serialization(self): - """ - Test serialization/deserialization for ListEnvironmentsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - environment_documents_model = {} # EnvironmentDocuments - - disk_usage_model = {} # DiskUsage - - collection_usage_model = {} # CollectionUsage - - index_capacity_model = {} # IndexCapacity - index_capacity_model['documents'] = environment_documents_model - index_capacity_model['disk_usage'] = disk_usage_model - index_capacity_model['collections'] = collection_usage_model - - search_status_model = {} # SearchStatus - search_status_model['scope'] = 'testString' - search_status_model['status'] = 'NO_DATA' - search_status_model['status_description'] = 'testString' - search_status_model['last_trained'] = '2019-01-01' - - environment_model = {} # Environment - environment_model['name'] = 'byod_environment' - environment_model['description'] = 'Private Data Environment' - environment_model['size'] = 'LT' - environment_model['requested_size'] = 'testString' - environment_model['index_capacity'] = index_capacity_model - environment_model['search_status'] = search_status_model - - # Construct a json representation of a ListEnvironmentsResponse model - list_environments_response_model_json = {} - list_environments_response_model_json['environments'] = [environment_model] - - # Construct a model instance of ListEnvironmentsResponse by calling from_dict on the json representation - list_environments_response_model = ListEnvironmentsResponse.from_dict(list_environments_response_model_json) - assert list_environments_response_model != False - - # Construct a model instance of ListEnvironmentsResponse by calling from_dict on the json representation - list_environments_response_model_dict = ListEnvironmentsResponse.from_dict(list_environments_response_model_json).__dict__ - list_environments_response_model2 = ListEnvironmentsResponse(**list_environments_response_model_dict) - - # Verify the model instances are equivalent - assert list_environments_response_model == list_environments_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_environments_response_model_json2 = list_environments_response_model.to_dict() - assert list_environments_response_model_json2 == list_environments_response_model_json - - -class TestModel_LogQueryResponse: - """ - Test Class for LogQueryResponse - """ - - def test_log_query_response_serialization(self): - """ - Test serialization/deserialization for LogQueryResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult - log_query_response_result_documents_result_model['position'] = 38 - log_query_response_result_documents_result_model['document_id'] = 'testString' - log_query_response_result_documents_result_model['score'] = 72.5 - log_query_response_result_documents_result_model['confidence'] = 72.5 - log_query_response_result_documents_result_model['collection_id'] = 'testString' - - log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments - log_query_response_result_documents_model['results'] = [log_query_response_result_documents_result_model] - log_query_response_result_documents_model['count'] = 38 - - log_query_response_result_model = {} # LogQueryResponseResult - log_query_response_result_model['environment_id'] = 'testString' - log_query_response_result_model['customer_id'] = 'testString' - log_query_response_result_model['document_type'] = 'query' - log_query_response_result_model['natural_language_query'] = 'testString' - log_query_response_result_model['document_results'] = log_query_response_result_documents_model - log_query_response_result_model['created_timestamp'] = '2019-01-01T12:00:00Z' - log_query_response_result_model['client_timestamp'] = '2019-01-01T12:00:00Z' - log_query_response_result_model['query_id'] = 'testString' - log_query_response_result_model['session_token'] = 'testString' - log_query_response_result_model['collection_id'] = 'testString' - log_query_response_result_model['display_rank'] = 38 - log_query_response_result_model['document_id'] = 'testString' - log_query_response_result_model['event_type'] = 'click' - log_query_response_result_model['result_type'] = 'document' - - # Construct a json representation of a LogQueryResponse model - log_query_response_model_json = {} - log_query_response_model_json['matching_results'] = 38 - log_query_response_model_json['results'] = [log_query_response_result_model] - - # Construct a model instance of LogQueryResponse by calling from_dict on the json representation - log_query_response_model = LogQueryResponse.from_dict(log_query_response_model_json) - assert log_query_response_model != False - - # Construct a model instance of LogQueryResponse by calling from_dict on the json representation - log_query_response_model_dict = LogQueryResponse.from_dict(log_query_response_model_json).__dict__ - log_query_response_model2 = LogQueryResponse(**log_query_response_model_dict) - - # Verify the model instances are equivalent - assert log_query_response_model == log_query_response_model2 - - # Convert model instance back to dict and verify no loss of data - log_query_response_model_json2 = log_query_response_model.to_dict() - assert log_query_response_model_json2 == log_query_response_model_json - - -class TestModel_LogQueryResponseResult: - """ - Test Class for LogQueryResponseResult - """ - - def test_log_query_response_result_serialization(self): - """ - Test serialization/deserialization for LogQueryResponseResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult - log_query_response_result_documents_result_model['position'] = 38 - log_query_response_result_documents_result_model['document_id'] = 'testString' - log_query_response_result_documents_result_model['score'] = 72.5 - log_query_response_result_documents_result_model['confidence'] = 72.5 - log_query_response_result_documents_result_model['collection_id'] = 'testString' - - log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments - log_query_response_result_documents_model['results'] = [log_query_response_result_documents_result_model] - log_query_response_result_documents_model['count'] = 38 - - # Construct a json representation of a LogQueryResponseResult model - log_query_response_result_model_json = {} - log_query_response_result_model_json['environment_id'] = 'testString' - log_query_response_result_model_json['customer_id'] = 'testString' - log_query_response_result_model_json['document_type'] = 'query' - log_query_response_result_model_json['natural_language_query'] = 'testString' - log_query_response_result_model_json['document_results'] = log_query_response_result_documents_model - log_query_response_result_model_json['created_timestamp'] = '2019-01-01T12:00:00Z' - log_query_response_result_model_json['client_timestamp'] = '2019-01-01T12:00:00Z' - log_query_response_result_model_json['query_id'] = 'testString' - log_query_response_result_model_json['session_token'] = 'testString' - log_query_response_result_model_json['collection_id'] = 'testString' - log_query_response_result_model_json['display_rank'] = 38 - log_query_response_result_model_json['document_id'] = 'testString' - log_query_response_result_model_json['event_type'] = 'click' - log_query_response_result_model_json['result_type'] = 'document' - - # Construct a model instance of LogQueryResponseResult by calling from_dict on the json representation - log_query_response_result_model = LogQueryResponseResult.from_dict(log_query_response_result_model_json) - assert log_query_response_result_model != False - - # Construct a model instance of LogQueryResponseResult by calling from_dict on the json representation - log_query_response_result_model_dict = LogQueryResponseResult.from_dict(log_query_response_result_model_json).__dict__ - log_query_response_result_model2 = LogQueryResponseResult(**log_query_response_result_model_dict) - - # Verify the model instances are equivalent - assert log_query_response_result_model == log_query_response_result_model2 - - # Convert model instance back to dict and verify no loss of data - log_query_response_result_model_json2 = log_query_response_result_model.to_dict() - assert log_query_response_result_model_json2 == log_query_response_result_model_json - - -class TestModel_LogQueryResponseResultDocuments: - """ - Test Class for LogQueryResponseResultDocuments - """ - - def test_log_query_response_result_documents_serialization(self): - """ - Test serialization/deserialization for LogQueryResponseResultDocuments - """ - - # Construct dict forms of any model objects needed in order to build this model. - - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult - log_query_response_result_documents_result_model['position'] = 38 - log_query_response_result_documents_result_model['document_id'] = 'testString' - log_query_response_result_documents_result_model['score'] = 72.5 - log_query_response_result_documents_result_model['confidence'] = 72.5 - log_query_response_result_documents_result_model['collection_id'] = 'testString' - - # Construct a json representation of a LogQueryResponseResultDocuments model - log_query_response_result_documents_model_json = {} - log_query_response_result_documents_model_json['results'] = [log_query_response_result_documents_result_model] - log_query_response_result_documents_model_json['count'] = 38 - - # Construct a model instance of LogQueryResponseResultDocuments by calling from_dict on the json representation - log_query_response_result_documents_model = LogQueryResponseResultDocuments.from_dict(log_query_response_result_documents_model_json) - assert log_query_response_result_documents_model != False - - # Construct a model instance of LogQueryResponseResultDocuments by calling from_dict on the json representation - log_query_response_result_documents_model_dict = LogQueryResponseResultDocuments.from_dict(log_query_response_result_documents_model_json).__dict__ - log_query_response_result_documents_model2 = LogQueryResponseResultDocuments(**log_query_response_result_documents_model_dict) - - # Verify the model instances are equivalent - assert log_query_response_result_documents_model == log_query_response_result_documents_model2 - - # Convert model instance back to dict and verify no loss of data - log_query_response_result_documents_model_json2 = log_query_response_result_documents_model.to_dict() - assert log_query_response_result_documents_model_json2 == log_query_response_result_documents_model_json - - -class TestModel_LogQueryResponseResultDocumentsResult: - """ - Test Class for LogQueryResponseResultDocumentsResult - """ - - def test_log_query_response_result_documents_result_serialization(self): - """ - Test serialization/deserialization for LogQueryResponseResultDocumentsResult - """ - - # Construct a json representation of a LogQueryResponseResultDocumentsResult model - log_query_response_result_documents_result_model_json = {} - log_query_response_result_documents_result_model_json['position'] = 38 - log_query_response_result_documents_result_model_json['document_id'] = 'testString' - log_query_response_result_documents_result_model_json['score'] = 72.5 - log_query_response_result_documents_result_model_json['confidence'] = 72.5 - log_query_response_result_documents_result_model_json['collection_id'] = 'testString' - - # Construct a model instance of LogQueryResponseResultDocumentsResult by calling from_dict on the json representation - log_query_response_result_documents_result_model = LogQueryResponseResultDocumentsResult.from_dict(log_query_response_result_documents_result_model_json) - assert log_query_response_result_documents_result_model != False - - # Construct a model instance of LogQueryResponseResultDocumentsResult by calling from_dict on the json representation - log_query_response_result_documents_result_model_dict = LogQueryResponseResultDocumentsResult.from_dict(log_query_response_result_documents_result_model_json).__dict__ - log_query_response_result_documents_result_model2 = LogQueryResponseResultDocumentsResult(**log_query_response_result_documents_result_model_dict) - - # Verify the model instances are equivalent - assert log_query_response_result_documents_result_model == log_query_response_result_documents_result_model2 - - # Convert model instance back to dict and verify no loss of data - log_query_response_result_documents_result_model_json2 = log_query_response_result_documents_result_model.to_dict() - assert log_query_response_result_documents_result_model_json2 == log_query_response_result_documents_result_model_json - - -class TestModel_MetricAggregation: - """ - Test Class for MetricAggregation - """ - - def test_metric_aggregation_serialization(self): - """ - Test serialization/deserialization for MetricAggregation - """ - - # Construct dict forms of any model objects needed in order to build this model. - - metric_aggregation_result_model = {} # MetricAggregationResult - metric_aggregation_result_model['key_as_string'] = '2019-01-01T12:00:00Z' - metric_aggregation_result_model['key'] = 26 - metric_aggregation_result_model['matching_results'] = 38 - metric_aggregation_result_model['event_rate'] = 72.5 - - # Construct a json representation of a MetricAggregation model - metric_aggregation_model_json = {} - metric_aggregation_model_json['interval'] = 'testString' - metric_aggregation_model_json['event_type'] = 'testString' - metric_aggregation_model_json['results'] = [metric_aggregation_result_model] - - # Construct a model instance of MetricAggregation by calling from_dict on the json representation - metric_aggregation_model = MetricAggregation.from_dict(metric_aggregation_model_json) - assert metric_aggregation_model != False - - # Construct a model instance of MetricAggregation by calling from_dict on the json representation - metric_aggregation_model_dict = MetricAggregation.from_dict(metric_aggregation_model_json).__dict__ - metric_aggregation_model2 = MetricAggregation(**metric_aggregation_model_dict) - - # Verify the model instances are equivalent - assert metric_aggregation_model == metric_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - metric_aggregation_model_json2 = metric_aggregation_model.to_dict() - assert metric_aggregation_model_json2 == metric_aggregation_model_json - - -class TestModel_MetricAggregationResult: - """ - Test Class for MetricAggregationResult - """ - - def test_metric_aggregation_result_serialization(self): - """ - Test serialization/deserialization for MetricAggregationResult - """ - - # Construct a json representation of a MetricAggregationResult model - metric_aggregation_result_model_json = {} - metric_aggregation_result_model_json['key_as_string'] = '2019-01-01T12:00:00Z' - metric_aggregation_result_model_json['key'] = 26 - metric_aggregation_result_model_json['matching_results'] = 38 - metric_aggregation_result_model_json['event_rate'] = 72.5 - - # Construct a model instance of MetricAggregationResult by calling from_dict on the json representation - metric_aggregation_result_model = MetricAggregationResult.from_dict(metric_aggregation_result_model_json) - assert metric_aggregation_result_model != False - - # Construct a model instance of MetricAggregationResult by calling from_dict on the json representation - metric_aggregation_result_model_dict = MetricAggregationResult.from_dict(metric_aggregation_result_model_json).__dict__ - metric_aggregation_result_model2 = MetricAggregationResult(**metric_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert metric_aggregation_result_model == metric_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - metric_aggregation_result_model_json2 = metric_aggregation_result_model.to_dict() - assert metric_aggregation_result_model_json2 == metric_aggregation_result_model_json - - -class TestModel_MetricResponse: - """ - Test Class for MetricResponse - """ - - def test_metric_response_serialization(self): - """ - Test serialization/deserialization for MetricResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - metric_aggregation_result_model = {} # MetricAggregationResult - metric_aggregation_result_model['key_as_string'] = '2019-01-01T12:00:00Z' - metric_aggregation_result_model['key'] = 26 - metric_aggregation_result_model['matching_results'] = 38 - metric_aggregation_result_model['event_rate'] = 72.5 - - metric_aggregation_model = {} # MetricAggregation - metric_aggregation_model['interval'] = 'testString' - metric_aggregation_model['event_type'] = 'testString' - metric_aggregation_model['results'] = [metric_aggregation_result_model] - - # Construct a json representation of a MetricResponse model - metric_response_model_json = {} - metric_response_model_json['aggregations'] = [metric_aggregation_model] - - # Construct a model instance of MetricResponse by calling from_dict on the json representation - metric_response_model = MetricResponse.from_dict(metric_response_model_json) - assert metric_response_model != False - - # Construct a model instance of MetricResponse by calling from_dict on the json representation - metric_response_model_dict = MetricResponse.from_dict(metric_response_model_json).__dict__ - metric_response_model2 = MetricResponse(**metric_response_model_dict) - - # Verify the model instances are equivalent - assert metric_response_model == metric_response_model2 - - # Convert model instance back to dict and verify no loss of data - metric_response_model_json2 = metric_response_model.to_dict() - assert metric_response_model_json2 == metric_response_model_json - - -class TestModel_MetricTokenAggregation: - """ - Test Class for MetricTokenAggregation - """ - - def test_metric_token_aggregation_serialization(self): - """ - Test serialization/deserialization for MetricTokenAggregation - """ - - # Construct dict forms of any model objects needed in order to build this model. - - metric_token_aggregation_result_model = {} # MetricTokenAggregationResult - metric_token_aggregation_result_model['key'] = 'testString' - metric_token_aggregation_result_model['matching_results'] = 38 - metric_token_aggregation_result_model['event_rate'] = 72.5 - - # Construct a json representation of a MetricTokenAggregation model - metric_token_aggregation_model_json = {} - metric_token_aggregation_model_json['event_type'] = 'testString' - metric_token_aggregation_model_json['results'] = [metric_token_aggregation_result_model] - - # Construct a model instance of MetricTokenAggregation by calling from_dict on the json representation - metric_token_aggregation_model = MetricTokenAggregation.from_dict(metric_token_aggregation_model_json) - assert metric_token_aggregation_model != False - - # Construct a model instance of MetricTokenAggregation by calling from_dict on the json representation - metric_token_aggregation_model_dict = MetricTokenAggregation.from_dict(metric_token_aggregation_model_json).__dict__ - metric_token_aggregation_model2 = MetricTokenAggregation(**metric_token_aggregation_model_dict) - - # Verify the model instances are equivalent - assert metric_token_aggregation_model == metric_token_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - metric_token_aggregation_model_json2 = metric_token_aggregation_model.to_dict() - assert metric_token_aggregation_model_json2 == metric_token_aggregation_model_json - - -class TestModel_MetricTokenAggregationResult: - """ - Test Class for MetricTokenAggregationResult - """ - - def test_metric_token_aggregation_result_serialization(self): - """ - Test serialization/deserialization for MetricTokenAggregationResult - """ - - # Construct a json representation of a MetricTokenAggregationResult model - metric_token_aggregation_result_model_json = {} - metric_token_aggregation_result_model_json['key'] = 'testString' - metric_token_aggregation_result_model_json['matching_results'] = 38 - metric_token_aggregation_result_model_json['event_rate'] = 72.5 - - # Construct a model instance of MetricTokenAggregationResult by calling from_dict on the json representation - metric_token_aggregation_result_model = MetricTokenAggregationResult.from_dict(metric_token_aggregation_result_model_json) - assert metric_token_aggregation_result_model != False - - # Construct a model instance of MetricTokenAggregationResult by calling from_dict on the json representation - metric_token_aggregation_result_model_dict = MetricTokenAggregationResult.from_dict(metric_token_aggregation_result_model_json).__dict__ - metric_token_aggregation_result_model2 = MetricTokenAggregationResult(**metric_token_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert metric_token_aggregation_result_model == metric_token_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - metric_token_aggregation_result_model_json2 = metric_token_aggregation_result_model.to_dict() - assert metric_token_aggregation_result_model_json2 == metric_token_aggregation_result_model_json - - -class TestModel_MetricTokenResponse: - """ - Test Class for MetricTokenResponse - """ - - def test_metric_token_response_serialization(self): - """ - Test serialization/deserialization for MetricTokenResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - metric_token_aggregation_result_model = {} # MetricTokenAggregationResult - metric_token_aggregation_result_model['key'] = 'testString' - metric_token_aggregation_result_model['matching_results'] = 38 - metric_token_aggregation_result_model['event_rate'] = 72.5 - - metric_token_aggregation_model = {} # MetricTokenAggregation - metric_token_aggregation_model['event_type'] = 'testString' - metric_token_aggregation_model['results'] = [metric_token_aggregation_result_model] - - # Construct a json representation of a MetricTokenResponse model - metric_token_response_model_json = {} - metric_token_response_model_json['aggregations'] = [metric_token_aggregation_model] - - # Construct a model instance of MetricTokenResponse by calling from_dict on the json representation - metric_token_response_model = MetricTokenResponse.from_dict(metric_token_response_model_json) - assert metric_token_response_model != False - - # Construct a model instance of MetricTokenResponse by calling from_dict on the json representation - metric_token_response_model_dict = MetricTokenResponse.from_dict(metric_token_response_model_json).__dict__ - metric_token_response_model2 = MetricTokenResponse(**metric_token_response_model_dict) - - # Verify the model instances are equivalent - assert metric_token_response_model == metric_token_response_model2 - - # Convert model instance back to dict and verify no loss of data - metric_token_response_model_json2 = metric_token_response_model.to_dict() - assert metric_token_response_model_json2 == metric_token_response_model_json - - -class TestModel_NluEnrichmentConcepts: - """ - Test Class for NluEnrichmentConcepts - """ - - def test_nlu_enrichment_concepts_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentConcepts - """ - - # Construct a json representation of a NluEnrichmentConcepts model - nlu_enrichment_concepts_model_json = {} - nlu_enrichment_concepts_model_json['limit'] = 38 - - # Construct a model instance of NluEnrichmentConcepts by calling from_dict on the json representation - nlu_enrichment_concepts_model = NluEnrichmentConcepts.from_dict(nlu_enrichment_concepts_model_json) - assert nlu_enrichment_concepts_model != False - - # Construct a model instance of NluEnrichmentConcepts by calling from_dict on the json representation - nlu_enrichment_concepts_model_dict = NluEnrichmentConcepts.from_dict(nlu_enrichment_concepts_model_json).__dict__ - nlu_enrichment_concepts_model2 = NluEnrichmentConcepts(**nlu_enrichment_concepts_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_concepts_model == nlu_enrichment_concepts_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_concepts_model_json2 = nlu_enrichment_concepts_model.to_dict() - assert nlu_enrichment_concepts_model_json2 == nlu_enrichment_concepts_model_json - - -class TestModel_NluEnrichmentEmotion: - """ - Test Class for NluEnrichmentEmotion - """ - - def test_nlu_enrichment_emotion_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentEmotion - """ - - # Construct a json representation of a NluEnrichmentEmotion model - nlu_enrichment_emotion_model_json = {} - nlu_enrichment_emotion_model_json['document'] = True - nlu_enrichment_emotion_model_json['targets'] = ['testString'] - - # Construct a model instance of NluEnrichmentEmotion by calling from_dict on the json representation - nlu_enrichment_emotion_model = NluEnrichmentEmotion.from_dict(nlu_enrichment_emotion_model_json) - assert nlu_enrichment_emotion_model != False - - # Construct a model instance of NluEnrichmentEmotion by calling from_dict on the json representation - nlu_enrichment_emotion_model_dict = NluEnrichmentEmotion.from_dict(nlu_enrichment_emotion_model_json).__dict__ - nlu_enrichment_emotion_model2 = NluEnrichmentEmotion(**nlu_enrichment_emotion_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_emotion_model == nlu_enrichment_emotion_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_emotion_model_json2 = nlu_enrichment_emotion_model.to_dict() - assert nlu_enrichment_emotion_model_json2 == nlu_enrichment_emotion_model_json - - -class TestModel_NluEnrichmentEntities: - """ - Test Class for NluEnrichmentEntities - """ - - def test_nlu_enrichment_entities_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentEntities - """ - - # Construct a json representation of a NluEnrichmentEntities model - nlu_enrichment_entities_model_json = {} - nlu_enrichment_entities_model_json['sentiment'] = True - nlu_enrichment_entities_model_json['emotion'] = True - nlu_enrichment_entities_model_json['limit'] = 38 - nlu_enrichment_entities_model_json['mentions'] = True - nlu_enrichment_entities_model_json['mention_types'] = True - nlu_enrichment_entities_model_json['sentence_locations'] = True - nlu_enrichment_entities_model_json['model'] = 'testString' - - # Construct a model instance of NluEnrichmentEntities by calling from_dict on the json representation - nlu_enrichment_entities_model = NluEnrichmentEntities.from_dict(nlu_enrichment_entities_model_json) - assert nlu_enrichment_entities_model != False - - # Construct a model instance of NluEnrichmentEntities by calling from_dict on the json representation - nlu_enrichment_entities_model_dict = NluEnrichmentEntities.from_dict(nlu_enrichment_entities_model_json).__dict__ - nlu_enrichment_entities_model2 = NluEnrichmentEntities(**nlu_enrichment_entities_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_entities_model == nlu_enrichment_entities_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_entities_model_json2 = nlu_enrichment_entities_model.to_dict() - assert nlu_enrichment_entities_model_json2 == nlu_enrichment_entities_model_json - - -class TestModel_NluEnrichmentFeatures: - """ - Test Class for NluEnrichmentFeatures - """ - - def test_nlu_enrichment_features_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentFeatures - """ - - # Construct dict forms of any model objects needed in order to build this model. - - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - nlu_enrichment_entities_model = {} # NluEnrichmentEntities - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - nlu_enrichment_relations_model = {} # NluEnrichmentRelations - nlu_enrichment_relations_model['model'] = 'testString' - - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts - nlu_enrichment_concepts_model['limit'] = 38 - - # Construct a json representation of a NluEnrichmentFeatures model - nlu_enrichment_features_model_json = {} - nlu_enrichment_features_model_json['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model_json['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model_json['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model_json['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model_json['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model_json['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model_json['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model_json['concepts'] = nlu_enrichment_concepts_model - - # Construct a model instance of NluEnrichmentFeatures by calling from_dict on the json representation - nlu_enrichment_features_model = NluEnrichmentFeatures.from_dict(nlu_enrichment_features_model_json) - assert nlu_enrichment_features_model != False - - # Construct a model instance of NluEnrichmentFeatures by calling from_dict on the json representation - nlu_enrichment_features_model_dict = NluEnrichmentFeatures.from_dict(nlu_enrichment_features_model_json).__dict__ - nlu_enrichment_features_model2 = NluEnrichmentFeatures(**nlu_enrichment_features_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_features_model == nlu_enrichment_features_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_features_model_json2 = nlu_enrichment_features_model.to_dict() - assert nlu_enrichment_features_model_json2 == nlu_enrichment_features_model_json - - -class TestModel_NluEnrichmentKeywords: - """ - Test Class for NluEnrichmentKeywords - """ - - def test_nlu_enrichment_keywords_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentKeywords - """ - - # Construct a json representation of a NluEnrichmentKeywords model - nlu_enrichment_keywords_model_json = {} - nlu_enrichment_keywords_model_json['sentiment'] = True - nlu_enrichment_keywords_model_json['emotion'] = True - nlu_enrichment_keywords_model_json['limit'] = 38 - - # Construct a model instance of NluEnrichmentKeywords by calling from_dict on the json representation - nlu_enrichment_keywords_model = NluEnrichmentKeywords.from_dict(nlu_enrichment_keywords_model_json) - assert nlu_enrichment_keywords_model != False - - # Construct a model instance of NluEnrichmentKeywords by calling from_dict on the json representation - nlu_enrichment_keywords_model_dict = NluEnrichmentKeywords.from_dict(nlu_enrichment_keywords_model_json).__dict__ - nlu_enrichment_keywords_model2 = NluEnrichmentKeywords(**nlu_enrichment_keywords_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_keywords_model == nlu_enrichment_keywords_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_keywords_model_json2 = nlu_enrichment_keywords_model.to_dict() - assert nlu_enrichment_keywords_model_json2 == nlu_enrichment_keywords_model_json - - -class TestModel_NluEnrichmentRelations: - """ - Test Class for NluEnrichmentRelations - """ - - def test_nlu_enrichment_relations_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentRelations - """ - - # Construct a json representation of a NluEnrichmentRelations model - nlu_enrichment_relations_model_json = {} - nlu_enrichment_relations_model_json['model'] = 'testString' - - # Construct a model instance of NluEnrichmentRelations by calling from_dict on the json representation - nlu_enrichment_relations_model = NluEnrichmentRelations.from_dict(nlu_enrichment_relations_model_json) - assert nlu_enrichment_relations_model != False - - # Construct a model instance of NluEnrichmentRelations by calling from_dict on the json representation - nlu_enrichment_relations_model_dict = NluEnrichmentRelations.from_dict(nlu_enrichment_relations_model_json).__dict__ - nlu_enrichment_relations_model2 = NluEnrichmentRelations(**nlu_enrichment_relations_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_relations_model == nlu_enrichment_relations_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_relations_model_json2 = nlu_enrichment_relations_model.to_dict() - assert nlu_enrichment_relations_model_json2 == nlu_enrichment_relations_model_json - - -class TestModel_NluEnrichmentSemanticRoles: - """ - Test Class for NluEnrichmentSemanticRoles - """ - - def test_nlu_enrichment_semantic_roles_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentSemanticRoles - """ - - # Construct a json representation of a NluEnrichmentSemanticRoles model - nlu_enrichment_semantic_roles_model_json = {} - nlu_enrichment_semantic_roles_model_json['entities'] = True - nlu_enrichment_semantic_roles_model_json['keywords'] = True - nlu_enrichment_semantic_roles_model_json['limit'] = 38 - - # Construct a model instance of NluEnrichmentSemanticRoles by calling from_dict on the json representation - nlu_enrichment_semantic_roles_model = NluEnrichmentSemanticRoles.from_dict(nlu_enrichment_semantic_roles_model_json) - assert nlu_enrichment_semantic_roles_model != False - - # Construct a model instance of NluEnrichmentSemanticRoles by calling from_dict on the json representation - nlu_enrichment_semantic_roles_model_dict = NluEnrichmentSemanticRoles.from_dict(nlu_enrichment_semantic_roles_model_json).__dict__ - nlu_enrichment_semantic_roles_model2 = NluEnrichmentSemanticRoles(**nlu_enrichment_semantic_roles_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_semantic_roles_model == nlu_enrichment_semantic_roles_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_semantic_roles_model_json2 = nlu_enrichment_semantic_roles_model.to_dict() - assert nlu_enrichment_semantic_roles_model_json2 == nlu_enrichment_semantic_roles_model_json - - -class TestModel_NluEnrichmentSentiment: - """ - Test Class for NluEnrichmentSentiment - """ - - def test_nlu_enrichment_sentiment_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentSentiment - """ - - # Construct a json representation of a NluEnrichmentSentiment model - nlu_enrichment_sentiment_model_json = {} - nlu_enrichment_sentiment_model_json['document'] = True - nlu_enrichment_sentiment_model_json['targets'] = ['testString'] - - # Construct a model instance of NluEnrichmentSentiment by calling from_dict on the json representation - nlu_enrichment_sentiment_model = NluEnrichmentSentiment.from_dict(nlu_enrichment_sentiment_model_json) - assert nlu_enrichment_sentiment_model != False - - # Construct a model instance of NluEnrichmentSentiment by calling from_dict on the json representation - nlu_enrichment_sentiment_model_dict = NluEnrichmentSentiment.from_dict(nlu_enrichment_sentiment_model_json).__dict__ - nlu_enrichment_sentiment_model2 = NluEnrichmentSentiment(**nlu_enrichment_sentiment_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_sentiment_model == nlu_enrichment_sentiment_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_sentiment_model_json2 = nlu_enrichment_sentiment_model.to_dict() - assert nlu_enrichment_sentiment_model_json2 == nlu_enrichment_sentiment_model_json - - -class TestModel_NormalizationOperation: - """ - Test Class for NormalizationOperation - """ - - def test_normalization_operation_serialization(self): - """ - Test serialization/deserialization for NormalizationOperation - """ - - # Construct a json representation of a NormalizationOperation model - normalization_operation_model_json = {} - normalization_operation_model_json['operation'] = 'copy' - normalization_operation_model_json['source_field'] = 'testString' - normalization_operation_model_json['destination_field'] = 'testString' - - # Construct a model instance of NormalizationOperation by calling from_dict on the json representation - normalization_operation_model = NormalizationOperation.from_dict(normalization_operation_model_json) - assert normalization_operation_model != False - - # Construct a model instance of NormalizationOperation by calling from_dict on the json representation - normalization_operation_model_dict = NormalizationOperation.from_dict(normalization_operation_model_json).__dict__ - normalization_operation_model2 = NormalizationOperation(**normalization_operation_model_dict) - - # Verify the model instances are equivalent - assert normalization_operation_model == normalization_operation_model2 - - # Convert model instance back to dict and verify no loss of data - normalization_operation_model_json2 = normalization_operation_model.to_dict() - assert normalization_operation_model_json2 == normalization_operation_model_json - - -class TestModel_Notice: - """ - Test Class for Notice - """ - - def test_notice_serialization(self): - """ - Test serialization/deserialization for Notice - """ - - # Construct a json representation of a Notice model - notice_model_json = {} - - # Construct a model instance of Notice by calling from_dict on the json representation - notice_model = Notice.from_dict(notice_model_json) - assert notice_model != False - - # Construct a model instance of Notice by calling from_dict on the json representation - notice_model_dict = Notice.from_dict(notice_model_json).__dict__ - notice_model2 = Notice(**notice_model_dict) - - # Verify the model instances are equivalent - assert notice_model == notice_model2 - - # Convert model instance back to dict and verify no loss of data - notice_model_json2 = notice_model.to_dict() - assert notice_model_json2 == notice_model_json - - -class TestModel_PdfHeadingDetection: - """ - Test Class for PdfHeadingDetection - """ - - def test_pdf_heading_detection_serialization(self): - """ - Test serialization/deserialization for PdfHeadingDetection - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - # Construct a json representation of a PdfHeadingDetection model - pdf_heading_detection_model_json = {} - pdf_heading_detection_model_json['fonts'] = [font_setting_model] - - # Construct a model instance of PdfHeadingDetection by calling from_dict on the json representation - pdf_heading_detection_model = PdfHeadingDetection.from_dict(pdf_heading_detection_model_json) - assert pdf_heading_detection_model != False - - # Construct a model instance of PdfHeadingDetection by calling from_dict on the json representation - pdf_heading_detection_model_dict = PdfHeadingDetection.from_dict(pdf_heading_detection_model_json).__dict__ - pdf_heading_detection_model2 = PdfHeadingDetection(**pdf_heading_detection_model_dict) - - # Verify the model instances are equivalent - assert pdf_heading_detection_model == pdf_heading_detection_model2 - - # Convert model instance back to dict and verify no loss of data - pdf_heading_detection_model_json2 = pdf_heading_detection_model.to_dict() - assert pdf_heading_detection_model_json2 == pdf_heading_detection_model_json - - -class TestModel_PdfSettings: - """ - Test Class for PdfSettings - """ - - def test_pdf_settings_serialization(self): - """ - Test serialization/deserialization for PdfSettings - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - pdf_heading_detection_model = {} # PdfHeadingDetection - pdf_heading_detection_model['fonts'] = [font_setting_model] - - # Construct a json representation of a PdfSettings model - pdf_settings_model_json = {} - pdf_settings_model_json['heading'] = pdf_heading_detection_model - - # Construct a model instance of PdfSettings by calling from_dict on the json representation - pdf_settings_model = PdfSettings.from_dict(pdf_settings_model_json) - assert pdf_settings_model != False - - # Construct a model instance of PdfSettings by calling from_dict on the json representation - pdf_settings_model_dict = PdfSettings.from_dict(pdf_settings_model_json).__dict__ - pdf_settings_model2 = PdfSettings(**pdf_settings_model_dict) - - # Verify the model instances are equivalent - assert pdf_settings_model == pdf_settings_model2 - - # Convert model instance back to dict and verify no loss of data - pdf_settings_model_json2 = pdf_settings_model.to_dict() - assert pdf_settings_model_json2 == pdf_settings_model_json - - -class TestModel_QueryAggregation: - """ - Test Class for QueryAggregation - """ - - def test_query_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryAggregation - """ - - # Construct a json representation of a QueryAggregation model - query_aggregation_model_json = {} - query_aggregation_model_json['type'] = 'testString' - - # Construct a model instance of QueryAggregation by calling from_dict on the json representation - query_aggregation_model = QueryAggregation.from_dict(query_aggregation_model_json) - assert query_aggregation_model != False - - # Construct a copy of the model instance by calling from_dict on the output of to_dict - query_aggregation_model_json2 = query_aggregation_model.to_dict() - query_aggregation_model2 = QueryAggregation.from_dict(query_aggregation_model_json2) - - # Verify the model instances are equivalent - assert query_aggregation_model == query_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_aggregation_model_json2 = query_aggregation_model.to_dict() - assert query_aggregation_model_json2 == query_aggregation_model_json - - -class TestModel_QueryHistogramAggregationResult: - """ - Test Class for QueryHistogramAggregationResult - """ - - def test_query_histogram_aggregation_result_serialization(self): - """ - Test serialization/deserialization for QueryHistogramAggregationResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - - # Construct a json representation of a QueryHistogramAggregationResult model - query_histogram_aggregation_result_model_json = {} - query_histogram_aggregation_result_model_json['key'] = 26 - query_histogram_aggregation_result_model_json['matching_results'] = 38 - query_histogram_aggregation_result_model_json['aggregations'] = [query_aggregation_model] - - # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation - query_histogram_aggregation_result_model = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json) - assert query_histogram_aggregation_result_model != False - - # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation - query_histogram_aggregation_result_model_dict = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json).__dict__ - query_histogram_aggregation_result_model2 = QueryHistogramAggregationResult(**query_histogram_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert query_histogram_aggregation_result_model == query_histogram_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_histogram_aggregation_result_model_json2 = query_histogram_aggregation_result_model.to_dict() - assert query_histogram_aggregation_result_model_json2 == query_histogram_aggregation_result_model_json - - -class TestModel_QueryNoticesResponse: - """ - Test Class for QueryNoticesResponse - """ - - def test_query_notices_response_serialization(self): - """ - Test serialization/deserialization for QueryNoticesResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_result_metadata_model = {} # QueryResultMetadata - query_result_metadata_model['score'] = 72.5 - query_result_metadata_model['confidence'] = 72.5 - - notice_model = {} # Notice - - query_notices_result_model = {} # QueryNoticesResult - query_notices_result_model['id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' - query_notices_result_model['metadata'] = {'anyKey': 'anyValue'} - query_notices_result_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' - query_notices_result_model['result_metadata'] = query_result_metadata_model - query_notices_result_model['code'] = 200 - query_notices_result_model['filename'] = 'instructions.html' - query_notices_result_model['file_type'] = 'html' - query_notices_result_model['sha1'] = 'de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3' - query_notices_result_model['notices'] = [notice_model] - query_notices_result_model['score'] = '1' - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - - query_passages_model = {} # QueryPassages - query_passages_model['document_id'] = 'testString' - query_passages_model['passage_score'] = 72.5 - query_passages_model['passage_text'] = 'testString' - query_passages_model['start_offset'] = 38 - query_passages_model['end_offset'] = 38 - query_passages_model['field'] = 'testString' - - # Construct a json representation of a QueryNoticesResponse model - query_notices_response_model_json = {} - query_notices_response_model_json['matching_results'] = 38 - query_notices_response_model_json['results'] = [query_notices_result_model] - query_notices_response_model_json['aggregations'] = [query_aggregation_model] - query_notices_response_model_json['passages'] = [query_passages_model] - query_notices_response_model_json['duplicates_removed'] = 38 - - # Construct a model instance of QueryNoticesResponse by calling from_dict on the json representation - query_notices_response_model = QueryNoticesResponse.from_dict(query_notices_response_model_json) - assert query_notices_response_model != False - - # Construct a model instance of QueryNoticesResponse by calling from_dict on the json representation - query_notices_response_model_dict = QueryNoticesResponse.from_dict(query_notices_response_model_json).__dict__ - query_notices_response_model2 = QueryNoticesResponse(**query_notices_response_model_dict) - - # Verify the model instances are equivalent - assert query_notices_response_model == query_notices_response_model2 - - # Convert model instance back to dict and verify no loss of data - query_notices_response_model_json2 = query_notices_response_model.to_dict() - assert query_notices_response_model_json2 == query_notices_response_model_json - - -class TestModel_QueryNoticesResult: - """ - Test Class for QueryNoticesResult - """ - - def test_query_notices_result_serialization(self): - """ - Test serialization/deserialization for QueryNoticesResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_result_metadata_model = {} # QueryResultMetadata - query_result_metadata_model['score'] = 72.5 - query_result_metadata_model['confidence'] = 72.5 - - notice_model = {} # Notice - - # Construct a json representation of a QueryNoticesResult model - query_notices_result_model_json = {} - query_notices_result_model_json['id'] = 'testString' - query_notices_result_model_json['metadata'] = {'anyKey': 'anyValue'} - query_notices_result_model_json['collection_id'] = 'testString' - query_notices_result_model_json['result_metadata'] = query_result_metadata_model - query_notices_result_model_json['code'] = 38 - query_notices_result_model_json['filename'] = 'testString' - query_notices_result_model_json['file_type'] = 'pdf' - query_notices_result_model_json['sha1'] = 'testString' - query_notices_result_model_json['notices'] = [notice_model] - query_notices_result_model_json['foo'] = 'testString' - - # Construct a model instance of QueryNoticesResult by calling from_dict on the json representation - query_notices_result_model = QueryNoticesResult.from_dict(query_notices_result_model_json) - assert query_notices_result_model != False - - # Construct a model instance of QueryNoticesResult by calling from_dict on the json representation - query_notices_result_model_dict = QueryNoticesResult.from_dict(query_notices_result_model_json).__dict__ - query_notices_result_model2 = QueryNoticesResult(**query_notices_result_model_dict) - - # Verify the model instances are equivalent - assert query_notices_result_model == query_notices_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_notices_result_model_json2 = query_notices_result_model.to_dict() - assert query_notices_result_model_json2 == query_notices_result_model_json - - # Test get_properties and set_properties methods. - query_notices_result_model.set_properties({}) - actual_dict = query_notices_result_model.get_properties() - assert actual_dict == {} - - expected_dict = {'foo': 'testString'} - query_notices_result_model.set_properties(expected_dict) - actual_dict = query_notices_result_model.get_properties() - assert actual_dict == expected_dict - - -class TestModel_QueryPassages: - """ - Test Class for QueryPassages - """ - - def test_query_passages_serialization(self): - """ - Test serialization/deserialization for QueryPassages - """ - - # Construct a json representation of a QueryPassages model - query_passages_model_json = {} - query_passages_model_json['document_id'] = 'testString' - query_passages_model_json['passage_score'] = 72.5 - query_passages_model_json['passage_text'] = 'testString' - query_passages_model_json['start_offset'] = 38 - query_passages_model_json['end_offset'] = 38 - query_passages_model_json['field'] = 'testString' - - # Construct a model instance of QueryPassages by calling from_dict on the json representation - query_passages_model = QueryPassages.from_dict(query_passages_model_json) - assert query_passages_model != False - - # Construct a model instance of QueryPassages by calling from_dict on the json representation - query_passages_model_dict = QueryPassages.from_dict(query_passages_model_json).__dict__ - query_passages_model2 = QueryPassages(**query_passages_model_dict) - - # Verify the model instances are equivalent - assert query_passages_model == query_passages_model2 - - # Convert model instance back to dict and verify no loss of data - query_passages_model_json2 = query_passages_model.to_dict() - assert query_passages_model_json2 == query_passages_model_json - - -class TestModel_QueryResponse: - """ - Test Class for QueryResponse - """ - - def test_query_response_serialization(self): - """ - Test serialization/deserialization for QueryResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_result_metadata_model = {} # QueryResultMetadata - query_result_metadata_model['score'] = 72.5 - query_result_metadata_model['confidence'] = 72.5 - - query_result_model = {} # QueryResult - query_result_model['id'] = 'watson-generated ID' - query_result_model['metadata'] = {'anyKey': 'anyValue'} - query_result_model['collection_id'] = 'testString' - query_result_model['result_metadata'] = query_result_metadata_model - query_result_model['score'] = '1' - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - - query_passages_model = {} # QueryPassages - query_passages_model['document_id'] = 'testString' - query_passages_model['passage_score'] = 72.5 - query_passages_model['passage_text'] = 'testString' - query_passages_model['start_offset'] = 38 - query_passages_model['end_offset'] = 38 - query_passages_model['field'] = 'testString' - - retrieval_details_model = {} # RetrievalDetails - retrieval_details_model['document_retrieval_strategy'] = 'untrained' - - # Construct a json representation of a QueryResponse model - query_response_model_json = {} - query_response_model_json['matching_results'] = 38 - query_response_model_json['results'] = [query_result_model] - query_response_model_json['aggregations'] = [query_aggregation_model] - query_response_model_json['passages'] = [query_passages_model] - query_response_model_json['duplicates_removed'] = 38 - query_response_model_json['session_token'] = 'testString' - query_response_model_json['retrieval_details'] = retrieval_details_model - query_response_model_json['suggested_query'] = 'testString' - - # Construct a model instance of QueryResponse by calling from_dict on the json representation - query_response_model = QueryResponse.from_dict(query_response_model_json) - assert query_response_model != False - - # Construct a model instance of QueryResponse by calling from_dict on the json representation - query_response_model_dict = QueryResponse.from_dict(query_response_model_json).__dict__ - query_response_model2 = QueryResponse(**query_response_model_dict) - - # Verify the model instances are equivalent - assert query_response_model == query_response_model2 - - # Convert model instance back to dict and verify no loss of data - query_response_model_json2 = query_response_model.to_dict() - assert query_response_model_json2 == query_response_model_json - - -class TestModel_QueryResult: - """ - Test Class for QueryResult - """ - - def test_query_result_serialization(self): - """ - Test serialization/deserialization for QueryResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_result_metadata_model = {} # QueryResultMetadata - query_result_metadata_model['score'] = 72.5 - query_result_metadata_model['confidence'] = 72.5 - - # Construct a json representation of a QueryResult model - query_result_model_json = {} - query_result_model_json['id'] = 'testString' - query_result_model_json['metadata'] = {'anyKey': 'anyValue'} - query_result_model_json['collection_id'] = 'testString' - query_result_model_json['result_metadata'] = query_result_metadata_model - query_result_model_json['foo'] = 'testString' - - # Construct a model instance of QueryResult by calling from_dict on the json representation - query_result_model = QueryResult.from_dict(query_result_model_json) - assert query_result_model != False - - # Construct a model instance of QueryResult by calling from_dict on the json representation - query_result_model_dict = QueryResult.from_dict(query_result_model_json).__dict__ - query_result_model2 = QueryResult(**query_result_model_dict) - - # Verify the model instances are equivalent - assert query_result_model == query_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_result_model_json2 = query_result_model.to_dict() - assert query_result_model_json2 == query_result_model_json - - # Test get_properties and set_properties methods. - query_result_model.set_properties({}) - actual_dict = query_result_model.get_properties() - assert actual_dict == {} - - expected_dict = {'foo': 'testString'} - query_result_model.set_properties(expected_dict) - actual_dict = query_result_model.get_properties() - assert actual_dict == expected_dict - - -class TestModel_QueryResultMetadata: - """ - Test Class for QueryResultMetadata - """ - - def test_query_result_metadata_serialization(self): - """ - Test serialization/deserialization for QueryResultMetadata - """ - - # Construct a json representation of a QueryResultMetadata model - query_result_metadata_model_json = {} - query_result_metadata_model_json['score'] = 72.5 - query_result_metadata_model_json['confidence'] = 72.5 - - # Construct a model instance of QueryResultMetadata by calling from_dict on the json representation - query_result_metadata_model = QueryResultMetadata.from_dict(query_result_metadata_model_json) - assert query_result_metadata_model != False - - # Construct a model instance of QueryResultMetadata by calling from_dict on the json representation - query_result_metadata_model_dict = QueryResultMetadata.from_dict(query_result_metadata_model_json).__dict__ - query_result_metadata_model2 = QueryResultMetadata(**query_result_metadata_model_dict) - - # Verify the model instances are equivalent - assert query_result_metadata_model == query_result_metadata_model2 - - # Convert model instance back to dict and verify no loss of data - query_result_metadata_model_json2 = query_result_metadata_model.to_dict() - assert query_result_metadata_model_json2 == query_result_metadata_model_json - - -class TestModel_QueryTermAggregationResult: - """ - Test Class for QueryTermAggregationResult - """ - - def test_query_term_aggregation_result_serialization(self): - """ - Test serialization/deserialization for QueryTermAggregationResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - - # Construct a json representation of a QueryTermAggregationResult model - query_term_aggregation_result_model_json = {} - query_term_aggregation_result_model_json['key'] = 'testString' - query_term_aggregation_result_model_json['matching_results'] = 38 - query_term_aggregation_result_model_json['relevancy'] = 72.5 - query_term_aggregation_result_model_json['total_matching_documents'] = 38 - query_term_aggregation_result_model_json['estimated_matching_documents'] = 38 - query_term_aggregation_result_model_json['aggregations'] = [query_aggregation_model] - - # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation - query_term_aggregation_result_model = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json) - assert query_term_aggregation_result_model != False - - # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation - query_term_aggregation_result_model_dict = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json).__dict__ - query_term_aggregation_result_model2 = QueryTermAggregationResult(**query_term_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert query_term_aggregation_result_model == query_term_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_term_aggregation_result_model_json2 = query_term_aggregation_result_model.to_dict() - assert query_term_aggregation_result_model_json2 == query_term_aggregation_result_model_json - - -class TestModel_QueryTimesliceAggregationResult: - """ - Test Class for QueryTimesliceAggregationResult - """ - - def test_query_timeslice_aggregation_result_serialization(self): - """ - Test serialization/deserialization for QueryTimesliceAggregationResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - - # Construct a json representation of a QueryTimesliceAggregationResult model - query_timeslice_aggregation_result_model_json = {} - query_timeslice_aggregation_result_model_json['key_as_string'] = 'testString' - query_timeslice_aggregation_result_model_json['key'] = 26 - query_timeslice_aggregation_result_model_json['matching_results'] = 26 - query_timeslice_aggregation_result_model_json['aggregations'] = [query_aggregation_model] - - # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation - query_timeslice_aggregation_result_model = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json) - assert query_timeslice_aggregation_result_model != False - - # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation - query_timeslice_aggregation_result_model_dict = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json).__dict__ - query_timeslice_aggregation_result_model2 = QueryTimesliceAggregationResult(**query_timeslice_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert query_timeslice_aggregation_result_model == query_timeslice_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_timeslice_aggregation_result_model_json2 = query_timeslice_aggregation_result_model.to_dict() - assert query_timeslice_aggregation_result_model_json2 == query_timeslice_aggregation_result_model_json - - -class TestModel_QueryTopHitsAggregationResult: - """ - Test Class for QueryTopHitsAggregationResult - """ - - def test_query_top_hits_aggregation_result_serialization(self): - """ - Test serialization/deserialization for QueryTopHitsAggregationResult - """ - - # Construct a json representation of a QueryTopHitsAggregationResult model - query_top_hits_aggregation_result_model_json = {} - query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{'anyKey': 'anyValue'}] - - # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation - query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) - assert query_top_hits_aggregation_result_model != False - - # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation - query_top_hits_aggregation_result_model_dict = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json).__dict__ - query_top_hits_aggregation_result_model2 = QueryTopHitsAggregationResult(**query_top_hits_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert query_top_hits_aggregation_result_model == query_top_hits_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() - assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json - - -class TestModel_RetrievalDetails: - """ - Test Class for RetrievalDetails - """ - - def test_retrieval_details_serialization(self): - """ - Test serialization/deserialization for RetrievalDetails - """ - - # Construct a json representation of a RetrievalDetails model - retrieval_details_model_json = {} - retrieval_details_model_json['document_retrieval_strategy'] = 'untrained' - - # Construct a model instance of RetrievalDetails by calling from_dict on the json representation - retrieval_details_model = RetrievalDetails.from_dict(retrieval_details_model_json) - assert retrieval_details_model != False - - # Construct a model instance of RetrievalDetails by calling from_dict on the json representation - retrieval_details_model_dict = RetrievalDetails.from_dict(retrieval_details_model_json).__dict__ - retrieval_details_model2 = RetrievalDetails(**retrieval_details_model_dict) - - # Verify the model instances are equivalent - assert retrieval_details_model == retrieval_details_model2 - - # Convert model instance back to dict and verify no loss of data - retrieval_details_model_json2 = retrieval_details_model.to_dict() - assert retrieval_details_model_json2 == retrieval_details_model_json - - -class TestModel_SduStatus: - """ - Test Class for SduStatus - """ - - def test_sdu_status_serialization(self): - """ - Test serialization/deserialization for SduStatus - """ - - # Construct dict forms of any model objects needed in order to build this model. - - sdu_status_custom_fields_model = {} # SduStatusCustomFields - sdu_status_custom_fields_model['defined'] = 26 - sdu_status_custom_fields_model['maximum_allowed'] = 26 - - # Construct a json representation of a SduStatus model - sdu_status_model_json = {} - sdu_status_model_json['enabled'] = True - sdu_status_model_json['total_annotated_pages'] = 26 - sdu_status_model_json['total_pages'] = 26 - sdu_status_model_json['total_documents'] = 26 - sdu_status_model_json['custom_fields'] = sdu_status_custom_fields_model - - # Construct a model instance of SduStatus by calling from_dict on the json representation - sdu_status_model = SduStatus.from_dict(sdu_status_model_json) - assert sdu_status_model != False - - # Construct a model instance of SduStatus by calling from_dict on the json representation - sdu_status_model_dict = SduStatus.from_dict(sdu_status_model_json).__dict__ - sdu_status_model2 = SduStatus(**sdu_status_model_dict) - - # Verify the model instances are equivalent - assert sdu_status_model == sdu_status_model2 - - # Convert model instance back to dict and verify no loss of data - sdu_status_model_json2 = sdu_status_model.to_dict() - assert sdu_status_model_json2 == sdu_status_model_json - - -class TestModel_SduStatusCustomFields: - """ - Test Class for SduStatusCustomFields - """ - - def test_sdu_status_custom_fields_serialization(self): - """ - Test serialization/deserialization for SduStatusCustomFields - """ - - # Construct a json representation of a SduStatusCustomFields model - sdu_status_custom_fields_model_json = {} - sdu_status_custom_fields_model_json['defined'] = 26 - sdu_status_custom_fields_model_json['maximum_allowed'] = 26 - - # Construct a model instance of SduStatusCustomFields by calling from_dict on the json representation - sdu_status_custom_fields_model = SduStatusCustomFields.from_dict(sdu_status_custom_fields_model_json) - assert sdu_status_custom_fields_model != False - - # Construct a model instance of SduStatusCustomFields by calling from_dict on the json representation - sdu_status_custom_fields_model_dict = SduStatusCustomFields.from_dict(sdu_status_custom_fields_model_json).__dict__ - sdu_status_custom_fields_model2 = SduStatusCustomFields(**sdu_status_custom_fields_model_dict) - - # Verify the model instances are equivalent - assert sdu_status_custom_fields_model == sdu_status_custom_fields_model2 - - # Convert model instance back to dict and verify no loss of data - sdu_status_custom_fields_model_json2 = sdu_status_custom_fields_model.to_dict() - assert sdu_status_custom_fields_model_json2 == sdu_status_custom_fields_model_json - - -class TestModel_SearchStatus: - """ - Test Class for SearchStatus - """ - - def test_search_status_serialization(self): - """ - Test serialization/deserialization for SearchStatus - """ - - # Construct a json representation of a SearchStatus model - search_status_model_json = {} - search_status_model_json['scope'] = 'testString' - search_status_model_json['status'] = 'NO_DATA' - search_status_model_json['status_description'] = 'testString' - search_status_model_json['last_trained'] = '2019-01-01' - - # Construct a model instance of SearchStatus by calling from_dict on the json representation - search_status_model = SearchStatus.from_dict(search_status_model_json) - assert search_status_model != False - - # Construct a model instance of SearchStatus by calling from_dict on the json representation - search_status_model_dict = SearchStatus.from_dict(search_status_model_json).__dict__ - search_status_model2 = SearchStatus(**search_status_model_dict) - - # Verify the model instances are equivalent - assert search_status_model == search_status_model2 - - # Convert model instance back to dict and verify no loss of data - search_status_model_json2 = search_status_model.to_dict() - assert search_status_model_json2 == search_status_model_json - - -class TestModel_SegmentSettings: - """ - Test Class for SegmentSettings - """ - - def test_segment_settings_serialization(self): - """ - Test serialization/deserialization for SegmentSettings - """ - - # Construct a json representation of a SegmentSettings model - segment_settings_model_json = {} - segment_settings_model_json['enabled'] = False - segment_settings_model_json['selector_tags'] = ['h1', 'h2'] - segment_settings_model_json['annotated_fields'] = ['testString'] - - # Construct a model instance of SegmentSettings by calling from_dict on the json representation - segment_settings_model = SegmentSettings.from_dict(segment_settings_model_json) - assert segment_settings_model != False - - # Construct a model instance of SegmentSettings by calling from_dict on the json representation - segment_settings_model_dict = SegmentSettings.from_dict(segment_settings_model_json).__dict__ - segment_settings_model2 = SegmentSettings(**segment_settings_model_dict) - - # Verify the model instances are equivalent - assert segment_settings_model == segment_settings_model2 - - # Convert model instance back to dict and verify no loss of data - segment_settings_model_json2 = segment_settings_model.to_dict() - assert segment_settings_model_json2 == segment_settings_model_json - - -class TestModel_Source: - """ - Test Class for Source - """ - - def test_source_serialization(self): - """ - Test serialization/deserialization for Source - """ - - # Construct dict forms of any model objects needed in order to build this model. - - source_schedule_model = {} # SourceSchedule - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - source_options_folder_model = {} # SourceOptionsFolder - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - source_options_object_model = {} # SourceOptionsObject - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - source_options_site_coll_model = {} # SourceOptionsSiteColl - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - source_options_web_crawl_model = {} # SourceOptionsWebCrawl - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - source_options_buckets_model = {} # SourceOptionsBuckets - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - source_options_model = {} # SourceOptions - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - # Construct a json representation of a Source model - source_model_json = {} - source_model_json['type'] = 'box' - source_model_json['credential_id'] = 'testString' - source_model_json['schedule'] = source_schedule_model - source_model_json['options'] = source_options_model - - # Construct a model instance of Source by calling from_dict on the json representation - source_model = Source.from_dict(source_model_json) - assert source_model != False - - # Construct a model instance of Source by calling from_dict on the json representation - source_model_dict = Source.from_dict(source_model_json).__dict__ - source_model2 = Source(**source_model_dict) - - # Verify the model instances are equivalent - assert source_model == source_model2 - - # Convert model instance back to dict and verify no loss of data - source_model_json2 = source_model.to_dict() - assert source_model_json2 == source_model_json - - -class TestModel_SourceOptions: - """ - Test Class for SourceOptions - """ - - def test_source_options_serialization(self): - """ - Test serialization/deserialization for SourceOptions - """ - - # Construct dict forms of any model objects needed in order to build this model. - - source_options_folder_model = {} # SourceOptionsFolder - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - source_options_object_model = {} # SourceOptionsObject - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - source_options_site_coll_model = {} # SourceOptionsSiteColl - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - source_options_web_crawl_model = {} # SourceOptionsWebCrawl - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - source_options_buckets_model = {} # SourceOptionsBuckets - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - # Construct a json representation of a SourceOptions model - source_options_model_json = {} - source_options_model_json['folders'] = [source_options_folder_model] - source_options_model_json['objects'] = [source_options_object_model] - source_options_model_json['site_collections'] = [source_options_site_coll_model] - source_options_model_json['urls'] = [source_options_web_crawl_model] - source_options_model_json['buckets'] = [source_options_buckets_model] - source_options_model_json['crawl_all_buckets'] = True - - # Construct a model instance of SourceOptions by calling from_dict on the json representation - source_options_model = SourceOptions.from_dict(source_options_model_json) - assert source_options_model != False - - # Construct a model instance of SourceOptions by calling from_dict on the json representation - source_options_model_dict = SourceOptions.from_dict(source_options_model_json).__dict__ - source_options_model2 = SourceOptions(**source_options_model_dict) - - # Verify the model instances are equivalent - assert source_options_model == source_options_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_model_json2 = source_options_model.to_dict() - assert source_options_model_json2 == source_options_model_json - - -class TestModel_SourceOptionsBuckets: - """ - Test Class for SourceOptionsBuckets - """ - - def test_source_options_buckets_serialization(self): - """ - Test serialization/deserialization for SourceOptionsBuckets - """ - - # Construct a json representation of a SourceOptionsBuckets model - source_options_buckets_model_json = {} - source_options_buckets_model_json['name'] = 'testString' - source_options_buckets_model_json['limit'] = 38 - - # Construct a model instance of SourceOptionsBuckets by calling from_dict on the json representation - source_options_buckets_model = SourceOptionsBuckets.from_dict(source_options_buckets_model_json) - assert source_options_buckets_model != False - - # Construct a model instance of SourceOptionsBuckets by calling from_dict on the json representation - source_options_buckets_model_dict = SourceOptionsBuckets.from_dict(source_options_buckets_model_json).__dict__ - source_options_buckets_model2 = SourceOptionsBuckets(**source_options_buckets_model_dict) - - # Verify the model instances are equivalent - assert source_options_buckets_model == source_options_buckets_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_buckets_model_json2 = source_options_buckets_model.to_dict() - assert source_options_buckets_model_json2 == source_options_buckets_model_json - - -class TestModel_SourceOptionsFolder: - """ - Test Class for SourceOptionsFolder - """ - - def test_source_options_folder_serialization(self): - """ - Test serialization/deserialization for SourceOptionsFolder - """ - - # Construct a json representation of a SourceOptionsFolder model - source_options_folder_model_json = {} - source_options_folder_model_json['owner_user_id'] = 'testString' - source_options_folder_model_json['folder_id'] = 'testString' - source_options_folder_model_json['limit'] = 38 - - # Construct a model instance of SourceOptionsFolder by calling from_dict on the json representation - source_options_folder_model = SourceOptionsFolder.from_dict(source_options_folder_model_json) - assert source_options_folder_model != False - - # Construct a model instance of SourceOptionsFolder by calling from_dict on the json representation - source_options_folder_model_dict = SourceOptionsFolder.from_dict(source_options_folder_model_json).__dict__ - source_options_folder_model2 = SourceOptionsFolder(**source_options_folder_model_dict) - - # Verify the model instances are equivalent - assert source_options_folder_model == source_options_folder_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_folder_model_json2 = source_options_folder_model.to_dict() - assert source_options_folder_model_json2 == source_options_folder_model_json - - -class TestModel_SourceOptionsObject: - """ - Test Class for SourceOptionsObject - """ - - def test_source_options_object_serialization(self): - """ - Test serialization/deserialization for SourceOptionsObject - """ - - # Construct a json representation of a SourceOptionsObject model - source_options_object_model_json = {} - source_options_object_model_json['name'] = 'testString' - source_options_object_model_json['limit'] = 38 - - # Construct a model instance of SourceOptionsObject by calling from_dict on the json representation - source_options_object_model = SourceOptionsObject.from_dict(source_options_object_model_json) - assert source_options_object_model != False - - # Construct a model instance of SourceOptionsObject by calling from_dict on the json representation - source_options_object_model_dict = SourceOptionsObject.from_dict(source_options_object_model_json).__dict__ - source_options_object_model2 = SourceOptionsObject(**source_options_object_model_dict) - - # Verify the model instances are equivalent - assert source_options_object_model == source_options_object_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_object_model_json2 = source_options_object_model.to_dict() - assert source_options_object_model_json2 == source_options_object_model_json - - -class TestModel_SourceOptionsSiteColl: - """ - Test Class for SourceOptionsSiteColl - """ - - def test_source_options_site_coll_serialization(self): - """ - Test serialization/deserialization for SourceOptionsSiteColl - """ - - # Construct a json representation of a SourceOptionsSiteColl model - source_options_site_coll_model_json = {} - source_options_site_coll_model_json['site_collection_path'] = 'testString' - source_options_site_coll_model_json['limit'] = 38 - - # Construct a model instance of SourceOptionsSiteColl by calling from_dict on the json representation - source_options_site_coll_model = SourceOptionsSiteColl.from_dict(source_options_site_coll_model_json) - assert source_options_site_coll_model != False - - # Construct a model instance of SourceOptionsSiteColl by calling from_dict on the json representation - source_options_site_coll_model_dict = SourceOptionsSiteColl.from_dict(source_options_site_coll_model_json).__dict__ - source_options_site_coll_model2 = SourceOptionsSiteColl(**source_options_site_coll_model_dict) - - # Verify the model instances are equivalent - assert source_options_site_coll_model == source_options_site_coll_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_site_coll_model_json2 = source_options_site_coll_model.to_dict() - assert source_options_site_coll_model_json2 == source_options_site_coll_model_json - - -class TestModel_SourceOptionsWebCrawl: - """ - Test Class for SourceOptionsWebCrawl - """ - - def test_source_options_web_crawl_serialization(self): - """ - Test serialization/deserialization for SourceOptionsWebCrawl - """ - - # Construct a json representation of a SourceOptionsWebCrawl model - source_options_web_crawl_model_json = {} - source_options_web_crawl_model_json['url'] = 'testString' - source_options_web_crawl_model_json['limit_to_starting_hosts'] = True - source_options_web_crawl_model_json['crawl_speed'] = 'normal' - source_options_web_crawl_model_json['allow_untrusted_certificate'] = False - source_options_web_crawl_model_json['maximum_hops'] = 2 - source_options_web_crawl_model_json['request_timeout'] = 30000 - source_options_web_crawl_model_json['override_robots_txt'] = False - source_options_web_crawl_model_json['blacklist'] = ['testString'] - - # Construct a model instance of SourceOptionsWebCrawl by calling from_dict on the json representation - source_options_web_crawl_model = SourceOptionsWebCrawl.from_dict(source_options_web_crawl_model_json) - assert source_options_web_crawl_model != False - - # Construct a model instance of SourceOptionsWebCrawl by calling from_dict on the json representation - source_options_web_crawl_model_dict = SourceOptionsWebCrawl.from_dict(source_options_web_crawl_model_json).__dict__ - source_options_web_crawl_model2 = SourceOptionsWebCrawl(**source_options_web_crawl_model_dict) - - # Verify the model instances are equivalent - assert source_options_web_crawl_model == source_options_web_crawl_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_web_crawl_model_json2 = source_options_web_crawl_model.to_dict() - assert source_options_web_crawl_model_json2 == source_options_web_crawl_model_json - - -class TestModel_SourceSchedule: - """ - Test Class for SourceSchedule - """ - - def test_source_schedule_serialization(self): - """ - Test serialization/deserialization for SourceSchedule - """ - - # Construct a json representation of a SourceSchedule model - source_schedule_model_json = {} - source_schedule_model_json['enabled'] = True - source_schedule_model_json['time_zone'] = 'America/New_York' - source_schedule_model_json['frequency'] = 'daily' - - # Construct a model instance of SourceSchedule by calling from_dict on the json representation - source_schedule_model = SourceSchedule.from_dict(source_schedule_model_json) - assert source_schedule_model != False - - # Construct a model instance of SourceSchedule by calling from_dict on the json representation - source_schedule_model_dict = SourceSchedule.from_dict(source_schedule_model_json).__dict__ - source_schedule_model2 = SourceSchedule(**source_schedule_model_dict) - - # Verify the model instances are equivalent - assert source_schedule_model == source_schedule_model2 - - # Convert model instance back to dict and verify no loss of data - source_schedule_model_json2 = source_schedule_model.to_dict() - assert source_schedule_model_json2 == source_schedule_model_json - - -class TestModel_SourceStatus: - """ - Test Class for SourceStatus - """ - - def test_source_status_serialization(self): - """ - Test serialization/deserialization for SourceStatus - """ - - # Construct a json representation of a SourceStatus model - source_status_model_json = {} - source_status_model_json['status'] = 'running' - source_status_model_json['next_crawl'] = '2019-01-01T12:00:00Z' - - # Construct a model instance of SourceStatus by calling from_dict on the json representation - source_status_model = SourceStatus.from_dict(source_status_model_json) - assert source_status_model != False - - # Construct a model instance of SourceStatus by calling from_dict on the json representation - source_status_model_dict = SourceStatus.from_dict(source_status_model_json).__dict__ - source_status_model2 = SourceStatus(**source_status_model_dict) - - # Verify the model instances are equivalent - assert source_status_model == source_status_model2 - - # Convert model instance back to dict and verify no loss of data - source_status_model_json2 = source_status_model.to_dict() - assert source_status_model_json2 == source_status_model_json - - -class TestModel_StatusDetails: - """ - Test Class for StatusDetails - """ - - def test_status_details_serialization(self): - """ - Test serialization/deserialization for StatusDetails - """ - - # Construct a json representation of a StatusDetails model - status_details_model_json = {} - status_details_model_json['authenticated'] = True - status_details_model_json['error_message'] = 'testString' - - # Construct a model instance of StatusDetails by calling from_dict on the json representation - status_details_model = StatusDetails.from_dict(status_details_model_json) - assert status_details_model != False - - # Construct a model instance of StatusDetails by calling from_dict on the json representation - status_details_model_dict = StatusDetails.from_dict(status_details_model_json).__dict__ - status_details_model2 = StatusDetails(**status_details_model_dict) - - # Verify the model instances are equivalent - assert status_details_model == status_details_model2 - - # Convert model instance back to dict and verify no loss of data - status_details_model_json2 = status_details_model.to_dict() - assert status_details_model_json2 == status_details_model_json - - -class TestModel_TokenDictRule: - """ - Test Class for TokenDictRule - """ - - def test_token_dict_rule_serialization(self): - """ - Test serialization/deserialization for TokenDictRule - """ - - # Construct a json representation of a TokenDictRule model - token_dict_rule_model_json = {} - token_dict_rule_model_json['text'] = 'testString' - token_dict_rule_model_json['tokens'] = ['testString'] - token_dict_rule_model_json['readings'] = ['testString'] - token_dict_rule_model_json['part_of_speech'] = 'testString' - - # Construct a model instance of TokenDictRule by calling from_dict on the json representation - token_dict_rule_model = TokenDictRule.from_dict(token_dict_rule_model_json) - assert token_dict_rule_model != False - - # Construct a model instance of TokenDictRule by calling from_dict on the json representation - token_dict_rule_model_dict = TokenDictRule.from_dict(token_dict_rule_model_json).__dict__ - token_dict_rule_model2 = TokenDictRule(**token_dict_rule_model_dict) - - # Verify the model instances are equivalent - assert token_dict_rule_model == token_dict_rule_model2 - - # Convert model instance back to dict and verify no loss of data - token_dict_rule_model_json2 = token_dict_rule_model.to_dict() - assert token_dict_rule_model_json2 == token_dict_rule_model_json - - -class TestModel_TokenDictStatusResponse: - """ - Test Class for TokenDictStatusResponse - """ - - def test_token_dict_status_response_serialization(self): - """ - Test serialization/deserialization for TokenDictStatusResponse - """ - - # Construct a json representation of a TokenDictStatusResponse model - token_dict_status_response_model_json = {} - token_dict_status_response_model_json['status'] = 'active' - token_dict_status_response_model_json['type'] = 'testString' - - # Construct a model instance of TokenDictStatusResponse by calling from_dict on the json representation - token_dict_status_response_model = TokenDictStatusResponse.from_dict(token_dict_status_response_model_json) - assert token_dict_status_response_model != False - - # Construct a model instance of TokenDictStatusResponse by calling from_dict on the json representation - token_dict_status_response_model_dict = TokenDictStatusResponse.from_dict(token_dict_status_response_model_json).__dict__ - token_dict_status_response_model2 = TokenDictStatusResponse(**token_dict_status_response_model_dict) - - # Verify the model instances are equivalent - assert token_dict_status_response_model == token_dict_status_response_model2 - - # Convert model instance back to dict and verify no loss of data - token_dict_status_response_model_json2 = token_dict_status_response_model.to_dict() - assert token_dict_status_response_model_json2 == token_dict_status_response_model_json - - -class TestModel_TrainingDataSet: - """ - Test Class for TrainingDataSet - """ - - def test_training_data_set_serialization(self): - """ - Test serialization/deserialization for TrainingDataSet - """ - - # Construct dict forms of any model objects needed in order to build this model. - - training_example_model = {} # TrainingExample - training_example_model['document_id'] = 'testString' - training_example_model['cross_reference'] = 'testString' - training_example_model['relevance'] = 38 - - training_query_model = {} # TrainingQuery - training_query_model['query_id'] = 'testString' - training_query_model['natural_language_query'] = 'testString' - training_query_model['filter'] = 'testString' - training_query_model['examples'] = [training_example_model] - - # Construct a json representation of a TrainingDataSet model - training_data_set_model_json = {} - training_data_set_model_json['environment_id'] = 'testString' - training_data_set_model_json['collection_id'] = 'testString' - training_data_set_model_json['queries'] = [training_query_model] - - # Construct a model instance of TrainingDataSet by calling from_dict on the json representation - training_data_set_model = TrainingDataSet.from_dict(training_data_set_model_json) - assert training_data_set_model != False - - # Construct a model instance of TrainingDataSet by calling from_dict on the json representation - training_data_set_model_dict = TrainingDataSet.from_dict(training_data_set_model_json).__dict__ - training_data_set_model2 = TrainingDataSet(**training_data_set_model_dict) - - # Verify the model instances are equivalent - assert training_data_set_model == training_data_set_model2 - - # Convert model instance back to dict and verify no loss of data - training_data_set_model_json2 = training_data_set_model.to_dict() - assert training_data_set_model_json2 == training_data_set_model_json - - -class TestModel_TrainingExample: - """ - Test Class for TrainingExample - """ - - def test_training_example_serialization(self): - """ - Test serialization/deserialization for TrainingExample - """ - - # Construct a json representation of a TrainingExample model - training_example_model_json = {} - training_example_model_json['document_id'] = 'testString' - training_example_model_json['cross_reference'] = 'testString' - training_example_model_json['relevance'] = 38 - - # Construct a model instance of TrainingExample by calling from_dict on the json representation - training_example_model = TrainingExample.from_dict(training_example_model_json) - assert training_example_model != False - - # Construct a model instance of TrainingExample by calling from_dict on the json representation - training_example_model_dict = TrainingExample.from_dict(training_example_model_json).__dict__ - training_example_model2 = TrainingExample(**training_example_model_dict) - - # Verify the model instances are equivalent - assert training_example_model == training_example_model2 - - # Convert model instance back to dict and verify no loss of data - training_example_model_json2 = training_example_model.to_dict() - assert training_example_model_json2 == training_example_model_json - - -class TestModel_TrainingExampleList: - """ - Test Class for TrainingExampleList - """ - - def test_training_example_list_serialization(self): - """ - Test serialization/deserialization for TrainingExampleList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - training_example_model = {} # TrainingExample - training_example_model['document_id'] = 'testString' - training_example_model['cross_reference'] = 'testString' - training_example_model['relevance'] = 38 - - # Construct a json representation of a TrainingExampleList model - training_example_list_model_json = {} - training_example_list_model_json['examples'] = [training_example_model] - - # Construct a model instance of TrainingExampleList by calling from_dict on the json representation - training_example_list_model = TrainingExampleList.from_dict(training_example_list_model_json) - assert training_example_list_model != False - - # Construct a model instance of TrainingExampleList by calling from_dict on the json representation - training_example_list_model_dict = TrainingExampleList.from_dict(training_example_list_model_json).__dict__ - training_example_list_model2 = TrainingExampleList(**training_example_list_model_dict) - - # Verify the model instances are equivalent - assert training_example_list_model == training_example_list_model2 - - # Convert model instance back to dict and verify no loss of data - training_example_list_model_json2 = training_example_list_model.to_dict() - assert training_example_list_model_json2 == training_example_list_model_json - - -class TestModel_TrainingQuery: - """ - Test Class for TrainingQuery - """ - - def test_training_query_serialization(self): - """ - Test serialization/deserialization for TrainingQuery - """ - - # Construct dict forms of any model objects needed in order to build this model. - - training_example_model = {} # TrainingExample - training_example_model['document_id'] = 'testString' - training_example_model['cross_reference'] = 'testString' - training_example_model['relevance'] = 38 - - # Construct a json representation of a TrainingQuery model - training_query_model_json = {} - training_query_model_json['query_id'] = 'testString' - training_query_model_json['natural_language_query'] = 'testString' - training_query_model_json['filter'] = 'testString' - training_query_model_json['examples'] = [training_example_model] - - # Construct a model instance of TrainingQuery by calling from_dict on the json representation - training_query_model = TrainingQuery.from_dict(training_query_model_json) - assert training_query_model != False - - # Construct a model instance of TrainingQuery by calling from_dict on the json representation - training_query_model_dict = TrainingQuery.from_dict(training_query_model_json).__dict__ - training_query_model2 = TrainingQuery(**training_query_model_dict) - - # Verify the model instances are equivalent - assert training_query_model == training_query_model2 - - # Convert model instance back to dict and verify no loss of data - training_query_model_json2 = training_query_model.to_dict() - assert training_query_model_json2 == training_query_model_json - - -class TestModel_TrainingStatus: - """ - Test Class for TrainingStatus - """ - - def test_training_status_serialization(self): - """ - Test serialization/deserialization for TrainingStatus - """ - - # Construct a json representation of a TrainingStatus model - training_status_model_json = {} - training_status_model_json['total_examples'] = 38 - training_status_model_json['available'] = True - training_status_model_json['processing'] = True - training_status_model_json['minimum_queries_added'] = True - training_status_model_json['minimum_examples_added'] = True - training_status_model_json['sufficient_label_diversity'] = True - training_status_model_json['notices'] = 38 - training_status_model_json['successfully_trained'] = '2019-01-01T12:00:00Z' - training_status_model_json['data_updated'] = '2019-01-01T12:00:00Z' - - # Construct a model instance of TrainingStatus by calling from_dict on the json representation - training_status_model = TrainingStatus.from_dict(training_status_model_json) - assert training_status_model != False - - # Construct a model instance of TrainingStatus by calling from_dict on the json representation - training_status_model_dict = TrainingStatus.from_dict(training_status_model_json).__dict__ - training_status_model2 = TrainingStatus(**training_status_model_dict) - - # Verify the model instances are equivalent - assert training_status_model == training_status_model2 - - # Convert model instance back to dict and verify no loss of data - training_status_model_json2 = training_status_model.to_dict() - assert training_status_model_json2 == training_status_model_json - - -class TestModel_WordHeadingDetection: - """ - Test Class for WordHeadingDetection - """ - - def test_word_heading_detection_serialization(self): - """ - Test serialization/deserialization for WordHeadingDetection - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - word_style_model = {} # WordStyle - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - # Construct a json representation of a WordHeadingDetection model - word_heading_detection_model_json = {} - word_heading_detection_model_json['fonts'] = [font_setting_model] - word_heading_detection_model_json['styles'] = [word_style_model] - - # Construct a model instance of WordHeadingDetection by calling from_dict on the json representation - word_heading_detection_model = WordHeadingDetection.from_dict(word_heading_detection_model_json) - assert word_heading_detection_model != False - - # Construct a model instance of WordHeadingDetection by calling from_dict on the json representation - word_heading_detection_model_dict = WordHeadingDetection.from_dict(word_heading_detection_model_json).__dict__ - word_heading_detection_model2 = WordHeadingDetection(**word_heading_detection_model_dict) - - # Verify the model instances are equivalent - assert word_heading_detection_model == word_heading_detection_model2 - - # Convert model instance back to dict and verify no loss of data - word_heading_detection_model_json2 = word_heading_detection_model.to_dict() - assert word_heading_detection_model_json2 == word_heading_detection_model_json - - -class TestModel_WordSettings: - """ - Test Class for WordSettings - """ - - def test_word_settings_serialization(self): - """ - Test serialization/deserialization for WordSettings - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - word_style_model = {} # WordStyle - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - word_heading_detection_model = {} # WordHeadingDetection - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - # Construct a json representation of a WordSettings model - word_settings_model_json = {} - word_settings_model_json['heading'] = word_heading_detection_model - - # Construct a model instance of WordSettings by calling from_dict on the json representation - word_settings_model = WordSettings.from_dict(word_settings_model_json) - assert word_settings_model != False - - # Construct a model instance of WordSettings by calling from_dict on the json representation - word_settings_model_dict = WordSettings.from_dict(word_settings_model_json).__dict__ - word_settings_model2 = WordSettings(**word_settings_model_dict) - - # Verify the model instances are equivalent - assert word_settings_model == word_settings_model2 - - # Convert model instance back to dict and verify no loss of data - word_settings_model_json2 = word_settings_model.to_dict() - assert word_settings_model_json2 == word_settings_model_json - - -class TestModel_WordStyle: - """ - Test Class for WordStyle - """ - - def test_word_style_serialization(self): - """ - Test serialization/deserialization for WordStyle - """ - - # Construct a json representation of a WordStyle model - word_style_model_json = {} - word_style_model_json['level'] = 38 - word_style_model_json['names'] = ['testString'] - - # Construct a model instance of WordStyle by calling from_dict on the json representation - word_style_model = WordStyle.from_dict(word_style_model_json) - assert word_style_model != False - - # Construct a model instance of WordStyle by calling from_dict on the json representation - word_style_model_dict = WordStyle.from_dict(word_style_model_json).__dict__ - word_style_model2 = WordStyle(**word_style_model_dict) - - # Verify the model instances are equivalent - assert word_style_model == word_style_model2 - - # Convert model instance back to dict and verify no loss of data - word_style_model_json2 = word_style_model.to_dict() - assert word_style_model_json2 == word_style_model_json - - -class TestModel_XPathPatterns: - """ - Test Class for XPathPatterns - """ - - def test_x_path_patterns_serialization(self): - """ - Test serialization/deserialization for XPathPatterns - """ - - # Construct a json representation of a XPathPatterns model - x_path_patterns_model_json = {} - x_path_patterns_model_json['xpaths'] = ['testString'] - - # Construct a model instance of XPathPatterns by calling from_dict on the json representation - x_path_patterns_model = XPathPatterns.from_dict(x_path_patterns_model_json) - assert x_path_patterns_model != False - - # Construct a model instance of XPathPatterns by calling from_dict on the json representation - x_path_patterns_model_dict = XPathPatterns.from_dict(x_path_patterns_model_json).__dict__ - x_path_patterns_model2 = XPathPatterns(**x_path_patterns_model_dict) - - # Verify the model instances are equivalent - assert x_path_patterns_model == x_path_patterns_model2 - - # Convert model instance back to dict and verify no loss of data - x_path_patterns_model_json2 = x_path_patterns_model.to_dict() - assert x_path_patterns_model_json2 == x_path_patterns_model_json - - -class TestModel_QueryCalculationAggregation: - """ - Test Class for QueryCalculationAggregation - """ - - def test_query_calculation_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryCalculationAggregation - """ - - # Construct a json representation of a QueryCalculationAggregation model - query_calculation_aggregation_model_json = {} - query_calculation_aggregation_model_json['type'] = 'unique_count' - query_calculation_aggregation_model_json['field'] = 'testString' - query_calculation_aggregation_model_json['value'] = 72.5 - - # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation - query_calculation_aggregation_model = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json) - assert query_calculation_aggregation_model != False - - # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation - query_calculation_aggregation_model_dict = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json).__dict__ - query_calculation_aggregation_model2 = QueryCalculationAggregation(**query_calculation_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_calculation_aggregation_model == query_calculation_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_calculation_aggregation_model_json2 = query_calculation_aggregation_model.to_dict() - assert query_calculation_aggregation_model_json2 == query_calculation_aggregation_model_json - - -class TestModel_QueryFilterAggregation: - """ - Test Class for QueryFilterAggregation - """ - - def test_query_filter_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryFilterAggregation - """ - - # Construct a json representation of a QueryFilterAggregation model - query_filter_aggregation_model_json = {} - query_filter_aggregation_model_json['type'] = 'filter' - query_filter_aggregation_model_json['match'] = 'testString' - query_filter_aggregation_model_json['matching_results'] = 26 - - # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation - query_filter_aggregation_model = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json) - assert query_filter_aggregation_model != False - - # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation - query_filter_aggregation_model_dict = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json).__dict__ - query_filter_aggregation_model2 = QueryFilterAggregation(**query_filter_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_filter_aggregation_model == query_filter_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_filter_aggregation_model_json2 = query_filter_aggregation_model.to_dict() - assert query_filter_aggregation_model_json2 == query_filter_aggregation_model_json - - -class TestModel_QueryHistogramAggregation: - """ - Test Class for QueryHistogramAggregation - """ - - def test_query_histogram_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryHistogramAggregation - """ - - # Construct a json representation of a QueryHistogramAggregation model - query_histogram_aggregation_model_json = {} - query_histogram_aggregation_model_json['type'] = 'histogram' - query_histogram_aggregation_model_json['field'] = 'testString' - query_histogram_aggregation_model_json['interval'] = 38 - query_histogram_aggregation_model_json['name'] = 'testString' - - # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation - query_histogram_aggregation_model = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json) - assert query_histogram_aggregation_model != False - - # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation - query_histogram_aggregation_model_dict = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json).__dict__ - query_histogram_aggregation_model2 = QueryHistogramAggregation(**query_histogram_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_histogram_aggregation_model == query_histogram_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_histogram_aggregation_model_json2 = query_histogram_aggregation_model.to_dict() - assert query_histogram_aggregation_model_json2 == query_histogram_aggregation_model_json - - -class TestModel_QueryNestedAggregation: - """ - Test Class for QueryNestedAggregation - """ - - def test_query_nested_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryNestedAggregation - """ - - # Construct a json representation of a QueryNestedAggregation model - query_nested_aggregation_model_json = {} - query_nested_aggregation_model_json['type'] = 'nested' - query_nested_aggregation_model_json['path'] = 'testString' - query_nested_aggregation_model_json['matching_results'] = 26 - - # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation - query_nested_aggregation_model = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json) - assert query_nested_aggregation_model != False - - # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation - query_nested_aggregation_model_dict = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json).__dict__ - query_nested_aggregation_model2 = QueryNestedAggregation(**query_nested_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_nested_aggregation_model == query_nested_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_nested_aggregation_model_json2 = query_nested_aggregation_model.to_dict() - assert query_nested_aggregation_model_json2 == query_nested_aggregation_model_json - - -class TestModel_QueryTermAggregation: - """ - Test Class for QueryTermAggregation - """ - - def test_query_term_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryTermAggregation - """ - - # Construct a json representation of a QueryTermAggregation model - query_term_aggregation_model_json = {} - query_term_aggregation_model_json['type'] = 'term' - query_term_aggregation_model_json['field'] = 'testString' - query_term_aggregation_model_json['count'] = 38 - query_term_aggregation_model_json['name'] = 'testString' - - # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation - query_term_aggregation_model = QueryTermAggregation.from_dict(query_term_aggregation_model_json) - assert query_term_aggregation_model != False - - # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation - query_term_aggregation_model_dict = QueryTermAggregation.from_dict(query_term_aggregation_model_json).__dict__ - query_term_aggregation_model2 = QueryTermAggregation(**query_term_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_term_aggregation_model == query_term_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_term_aggregation_model_json2 = query_term_aggregation_model.to_dict() - assert query_term_aggregation_model_json2 == query_term_aggregation_model_json - - -class TestModel_QueryTimesliceAggregation: - """ - Test Class for QueryTimesliceAggregation - """ - - def test_query_timeslice_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryTimesliceAggregation - """ - - # Construct a json representation of a QueryTimesliceAggregation model - query_timeslice_aggregation_model_json = {} - query_timeslice_aggregation_model_json['type'] = 'timeslice' - query_timeslice_aggregation_model_json['field'] = 'testString' - query_timeslice_aggregation_model_json['interval'] = 'testString' - query_timeslice_aggregation_model_json['name'] = 'testString' - - # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation - query_timeslice_aggregation_model = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json) - assert query_timeslice_aggregation_model != False - - # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation - query_timeslice_aggregation_model_dict = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json).__dict__ - query_timeslice_aggregation_model2 = QueryTimesliceAggregation(**query_timeslice_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_timeslice_aggregation_model == query_timeslice_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_timeslice_aggregation_model_json2 = query_timeslice_aggregation_model.to_dict() - assert query_timeslice_aggregation_model_json2 == query_timeslice_aggregation_model_json - - -class TestModel_QueryTopHitsAggregation: - """ - Test Class for QueryTopHitsAggregation - """ - - def test_query_top_hits_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryTopHitsAggregation - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult - query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{'anyKey': 'anyValue'}] - - # Construct a json representation of a QueryTopHitsAggregation model - query_top_hits_aggregation_model_json = {} - query_top_hits_aggregation_model_json['type'] = 'top_hits' - query_top_hits_aggregation_model_json['size'] = 38 - query_top_hits_aggregation_model_json['name'] = 'testString' - query_top_hits_aggregation_model_json['hits'] = query_top_hits_aggregation_result_model - - # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation - query_top_hits_aggregation_model = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json) - assert query_top_hits_aggregation_model != False - - # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation - query_top_hits_aggregation_model_dict = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json).__dict__ - query_top_hits_aggregation_model2 = QueryTopHitsAggregation(**query_top_hits_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_top_hits_aggregation_model == query_top_hits_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_top_hits_aggregation_model_json2 = query_top_hits_aggregation_model.to_dict() - assert query_top_hits_aggregation_model_json2 == query_top_hits_aggregation_model_json - - -# endregion -############################################################################## -# End of Model Tests -############################################################################## From 9b22fb562ff6e742b0c90a0acf75cfda927e10b6 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 17 Oct 2024 13:19:18 -0500 Subject: [PATCH 06/11] feat(lt): remove lt and other deprecated resources BREAKING CHANGE: LanguageTranslator functionality has been removed --- .github/workflows/integration-test.yml | 3 - examples/language_translator_v3.py | 74 - ibm_watson/__init__.py | 1 - ibm_watson/language_translator_v3.py | 2369 ----------------- setup.py | 10 +- .../test_language_translator_v3.py | 53 - test/unit/test_language_translator_v3.py | 1841 ------------- 7 files changed, 5 insertions(+), 4346 deletions(-) delete mode 100644 examples/language_translator_v3.py delete mode 100644 ibm_watson/language_translator_v3.py delete mode 100644 test/integration/test_language_translator_v3.py delete mode 100644 test/unit/test_language_translator_v3.py diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index 4f55f471..d95c423b 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -35,8 +35,6 @@ jobs: - name: Execute Python integration tests # continue-on-error: true env: - LANGUAGE_TRANSLATOR_APIKEY: ${{ secrets.LT_APIKEY }} - LANGUAGE_TRANSLATOR_URL: "https://api.us-south.language-translator.watson.cloud.ibm.com" NATURAL_LANGUAGE_UNDERSTANDING_APIKEY: ${{ secrets.NLU_APIKEY }} NATURAL_LANGUAGE_UNDERSTANDING_URL: "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com" SPEECH_TO_TEXT_APIKEY: ${{ secrets.STT_APIKEY }} @@ -54,7 +52,6 @@ jobs: run: | pip3 install -U python-dotenv pytest test/integration/test_discovery_v2.py -rap - pytest test/integration/test_language_translator_v3.py -rap pytest test/integration/test_natural_language_understanding_v1.py -rap pytest test/integration/test_speech_to_text_v1.py -rap pytest test/integration/test_text_to_speech_v1.py -rap diff --git a/examples/language_translator_v3.py b/examples/language_translator_v3.py deleted file mode 100644 index da7aecf8..00000000 --- a/examples/language_translator_v3.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -import json -from ibm_watson import LanguageTranslatorV3 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your_api_key') -language_translator = LanguageTranslatorV3( - version='2018-05-01', - authenticator=authenticator) -language_translator.set_service_url('https://api.us-south.language-translator.watson.cloud.ibm.com') - -## Translate -translation = language_translator.translate( - text='Hello', model_id='en-es').get_result() -print(json.dumps(translation, indent=2, ensure_ascii=False)) - -# List identifiable languages -# languages = language_translator.list_identifiable_languages().get_result() -# print(json.dumps(languages, indent=2)) - -# # Identify -# language = language_translator.identify( -# 'Language translator translates text from one language to another').get_result() -# print(json.dumps(language, indent=2)) - -# # List models -# models = language_translator.list_models( -# source='en').get_result() -# print(json.dumps(models, indent=2)) - -# # Create model -# with open('glossary.tmx', 'rb') as glossary: -# response = language_translator.create_model( -# base_model_id='en-es', -# name='custom-english-to-spanish', -# forced_glossary=glossary).get_result() -# print(json.dumps(response, indent=2)) - -# # Delete model -# response = language_translator.delete_model(model_id='').get_result() -# print(json.dumps(response, indent=2)) - -# # 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}') diff --git a/ibm_watson/__init__.py b/ibm_watson/__init__.py index 12ace99e..aaa76799 100755 --- a/ibm_watson/__init__.py +++ b/ibm_watson/__init__.py @@ -17,7 +17,6 @@ from .assistant_v1 import AssistantV1 from .assistant_v2 import AssistantV2 -from .language_translator_v3 import LanguageTranslatorV3 from .natural_language_understanding_v1 import NaturalLanguageUnderstandingV1 from .text_to_speech_v1 import TextToSpeechV1 from .discovery_v2 import DiscoveryV2 diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py deleted file mode 100644 index ea5be9f6..00000000 --- a/ibm_watson/language_translator_v3.py +++ /dev/null @@ -1,2369 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2019, 2024. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# 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. - -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 -""" -IBM® is announcing the deprecation of the Watson® Language Translator service for -IBM Cloud® in all regions. As of 10 June 2023, the Language Translator tile will be -removed from the IBM Cloud Platform for new customers; only existing customers will be -able to access the product. As of 10 June 2024, the service will reach its End of Support -date. As of 10 December 2024, the service will be withdrawn entirely and will no longer be -available to any customers.{: deprecated} -IBM Watson™ Language Translator translates text from one language to another. The -service offers multiple IBM-provided translation models that you can customize based on -your unique terminology and language. Use Language Translator to take news from across the -globe and present it in your language, communicate with your customers in their own -language, and more. - -API Version: 3.0.0 -See: https://cloud.ibm.com/docs/language-translator -""" - -from datetime import datetime -from enum import Enum -from os.path import basename -from typing import BinaryIO, Dict, List, Optional, TextIO, Union -import json - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class LanguageTranslatorV3(BaseService): - """The Language Translator V3 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.language-translator.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'language_translator' - - def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Language Translator service. - - :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2018-05-01`. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md - about initializing the authenticator of your choice. - """ - if version is None: - raise ValueError('version must be provided') - - print(""" - On 10 June 2023, IBM announced the deprecation of the Natural Language Translator service. - The service will no longer be available from 8 August 2022. As of 10 June 2024, the service will reach its End of Support - date. As of 10 December 2024, the service will be withdrawn entirely and will no longer be - available to any customers. - """) - - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.version = version - self.configure_service(service_name) - - ######################### - # Languages - ######################### - - def list_languages( - self, - **kwargs, - ) -> DetailedResponse: - """ - List supported languages. - - Lists all supported languages for translation. The method returns an array of - supported languages with information about each language. Languages are listed in - alphabetical order by language code (for example, `af`, `ar`). In addition to - basic information about each language, the response indicates whether the language - is `supported_as_source` for translation and `supported_as_target` for - translation. It also lists whether the language is `identifiable`. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Languages` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_languages', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/languages' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Translation - ######################### - - def translate( - self, - text: List[str], - *, - model_id: Optional[str] = None, - source: Optional[str] = None, - target: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Translate. - - Translates the input text from the source language to the target language. Specify - a model ID that indicates the source and target languages, or specify the source - and target languages individually. You can omit the source language to have the - service attempt to detect the language from the input text. If you omit the source - language, the request must contain sufficient input text for the service to - identify the source language. - You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. - All input text must be encoded in UTF-8 format. - - :param List[str] text: Input text in UTF-8 encoding. Submit a maximum of 50 - KB (51,200 bytes) of text with a single request. Multiple elements result - in multiple translations in the response. - :param str model_id: (optional) The model to use for translation. For - example, `en-de` selects the IBM-provided base model for English-to-German - translation. A model ID overrides the `source` and `target` parameters and - is required if you use a custom model. If no model ID is specified, you - must specify at least a target language. - :param str source: (optional) Language code that specifies the language of - the input text. If omitted, the service derives the source language from - the input text. The input must contain sufficient text for the service to - identify the language reliably. - :param str target: (optional) Language code that specifies the target - language for translation. Required if model ID is not specified. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationResult` object - """ - - if text is None: - raise ValueError('text must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='translate', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'text': text, - 'model_id': model_id, - 'source': source, - 'target': target, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data, ensure_ascii=False).encode('utf-8') - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/translate' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Identification - ######################### - - def list_identifiable_languages( - self, - **kwargs, - ) -> DetailedResponse: - """ - List identifiable languages. - - Lists the languages that the service can identify. Returns the language code (for - example, `en` for English or `es` for Spanish) and name of each language. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `IdentifiableLanguages` object - """ - - headers = {} - 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, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/identifiable_languages' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def identify( - self, - text: Union[str, TextIO], - **kwargs, - ) -> DetailedResponse: - """ - Identify language. - - Identifies the language of the input text. - - :param str text: Input text in UTF-8 format. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `IdentifiedLanguages` object - """ - - if not text: - raise ValueError('text must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='identify', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = text - headers['content-type'] = 'text/plain' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/identify' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Models - ######################### - - def list_models( - self, - *, - source: Optional[str] = None, - target: Optional[str] = None, - default: Optional[bool] = None, - **kwargs, - ) -> DetailedResponse: - """ - List models. - - Lists available translation models. - - :param str source: (optional) Specify a language code to filter results by - source language. - :param str target: (optional) Specify a language code to filter results by - target language. - :param bool default: (optional) If the `default` parameter isn't specified, - the service returns all models (default and non-default) for each language - pair. To return only default models, set this parameter to `true`. To - return only non-default models, set this parameter to `false`. There is - exactly one default model, the IBM-provided base model, per language pair. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationModels` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_models', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'source': source, - 'target': target, - 'default': default, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/models' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_model( - self, - base_model_id: str, - *, - forced_glossary: Optional[BinaryIO] = None, - forced_glossary_content_type: Optional[str] = None, - parallel_corpus: Optional[BinaryIO] = None, - parallel_corpus_content_type: Optional[str] = None, - name: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create model. - - Uploads training files to customize a translation model. You can customize a model - with a forced glossary or with a parallel corpus: - * Use a *forced glossary* to force certain terms and phrases to be translated in a - specific way. You can upload only a single forced glossary file for a model. The - size of a forced glossary file for a custom model is limited to 10 MB. - * Use a *parallel corpus* when you want your custom model to learn from general - translation patterns in parallel sentences in your samples. What your model learns - from a parallel corpus can improve translation results for input text that the - model has not been trained on. You can upload multiple parallel corpora files with - a request. To successfully train with parallel corpora, the corpora files must - contain a cumulative total of at least 5000 parallel sentences. The cumulative - size of all uploaded corpus files for a custom model is limited to 250 MB. - Depending on the type of customization and the size of the uploaded files, - training time can range from minutes for a glossary to several hours for a large - parallel corpus. To create a model that is customized with a parallel corpus and a - forced glossary, customize the model with a parallel corpus first and then - customize the resulting model with a forced glossary. - You can create a maximum of 10 custom models per language pair. For more - information about customizing a translation model, including the formatting and - character restrictions for data files, see [Customizing your - model](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing). - #### Supported file formats - You can provide your training data for customization in the following document - formats: - * **TMX** (`.tmx`) - Translation Memory eXchange (TMX) is an XML specification for - the exchange of translation memories. - * **XLIFF** (`.xliff`) - XML Localization Interchange File Format (XLIFF) is an - XML specification for the exchange of translation memories. - * **CSV** (`.csv`) - Comma-separated values (CSV) file with two columns for - aligned sentences and phrases. The first row must have two language codes. The - first column is for the source language code, and the second column is for the - target language code. - * **TSV** (`.tsv` or `.tab`) - Tab-separated values (TSV) file with two columns - for aligned sentences and phrases. The first row must have two language codes. The - first column is for the source language code, and the second column is for the - target language code. - * **JSON** (`.json`) - Custom JSON format for specifying aligned sentences and - phrases. - * **Microsoft Excel** (`.xls` or `.xlsx`) - Excel file with the first two columns - for aligned sentences and phrases. The first row contains the language code. - You must encode all text data in UTF-8 format. For more information, see - [Supported document formats for training - data](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing#supported-document-formats-for-training-data). - #### Specifying file formats - You can indicate the format of a file by including the file extension with the - file name. Use the file extensions shown in **Supported file formats**. - Alternatively, you can omit the file extension and specify one of the following - `content-type` specifications for the file: - * **TMX** - `application/x-tmx+xml` - * **XLIFF** - `application/xliff+xml` - * **CSV** - `text/csv` - * **TSV** - `text/tab-separated-values` - * **JSON** - `application/json` - * **Microsoft Excel** - - `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` - For example, with `curl`, use the following `content-type` specification to - indicate the format of a CSV file named **glossary**: - `--form "forced_glossary=@glossary;type=text/csv"`. - - :param str base_model_id: The ID of the translation model to use as the - base for customization. To see available models and IDs, use the `List - models` method. Most models that are provided with the service are - customizable. In addition, all models that you create with parallel corpora - customization can be further customized with a forced glossary. - :param BinaryIO forced_glossary: (optional) A file with forced glossary - terms for the source and target languages. The customizations in the file - completely overwrite the domain translation data, including high frequency - or high confidence phrase translations. - You can upload only one glossary file for a custom model, and the glossary - can have a maximum size of 10 MB. A forced glossary must contain single - words or short phrases. For more information, see **Supported file - formats** in the method description. - *With `curl`, use `--form forced_glossary=@{filename}`.*. - :param str forced_glossary_content_type: (optional) The content type of - forced_glossary. - :param BinaryIO parallel_corpus: (optional) A file with parallel sentences - for the source and target languages. You can upload multiple parallel - corpus files in one request by repeating the parameter. All uploaded - parallel corpus files combined must contain at least 5000 parallel - sentences to train successfully. You can provide a maximum of 500,000 - parallel sentences across all corpora. - A single entry in a corpus file can contain a maximum of 80 words. All - corpora files for a custom model can have a cumulative maximum size of 250 - MB. For more information, see **Supported file formats** in the method - description. - *With `curl`, use `--form parallel_corpus=@{filename}`.*. - :param str parallel_corpus_content_type: (optional) The content type of - parallel_corpus. - :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 of the name is 32 - characters. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object - """ - - if not base_model_id: - raise ValueError('base_model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='create_model', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'base_model_id': base_model_id, - 'name': name, - } - - form_data = [] - if forced_glossary: - form_data.append( - ('forced_glossary', - (None, forced_glossary, forced_glossary_content_type or - 'application/octet-stream'))) - if parallel_corpus: - form_data.append( - ('parallel_corpus', - (None, parallel_corpus, parallel_corpus_content_type or - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/models' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_model( - self, - model_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete model. - - Deletes a custom translation model. - - :param str model_id: Model ID of the model to delete. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteModelResult` object - """ - - if not model_id: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_model', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_model( - self, - model_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get model details. - - Gets information about a translation model, including training status for custom - models. Use this method to poll the status of your customization request. A - successfully completed training request has a status of `available`. - - :param str model_id: Model ID of the model to get. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object - """ - - if not model_id: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_model', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Document translation - ######################### - - def list_documents( - self, - **kwargs, - ) -> DetailedResponse: - """ - List documents. - - Lists documents that have been submitted for translation. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentList` object - """ - - headers = {} - 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, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/documents' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def translate_document( - self, - file: BinaryIO, - *, - filename: Optional[str] = None, - file_content_type: Optional[str] = None, - model_id: Optional[str] = None, - source: Optional[str] = None, - target: Optional[str] = None, - document_id: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Translate document. - - Submit a document for translation. You can submit the document contents in the - `file` parameter, or you can specify a previously submitted document by document - ID. The maximum file size for document translation is - * **2 MB** for service instances on the Lite plan - * **20 MB** for service instances on the Standard plan - * **50 MB** for service instances on the Advanced plan - * **150 MB** for service instances on the Premium plan - You can specify the format of the file to be translated in one of two ways: - * By specifying the appropriate file extension for the format. - * By specifying the content type (MIME type) of the format as the `type` of the - `file` parameter. - In some cases, especially for subtitle file formats, you must use either the file - extension or the content type. For more information about all supported file - formats, their file extensions and content types, and how and when to specify the - file extension or content type, see [Supported file - formats](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). - **Note:** When translating a previously submitted document, the target language - must be different from the target language of the original request when the - document was initially submitted. - - :param BinaryIO file: The contents of the source file to translate. The - maximum file size for document translation is - * **2 MB** for service instances on the Lite plan - * **20 MB** for service instances on the Standard plan - * **50 MB** for service instances on the Advanced plan - * **150 MB** for service instances on the Premium plan - You can specify the format of the file to be translated in one of two ways: - * By specifying the appropriate file extension for the format. - * By specifying the content type (MIME type) of the format as the `type` of - the `file` parameter. - In some cases, especially for subtitle file formats, you must use either - the file extension or the content type. - For more information about all supported file formats, their file - extensions and content types, and how and when to specify the file - extension or content type, see [Supported file - formats](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str model_id: (optional) The model to use for translation. For - example, `en-de` selects the IBM-provided base model for English-to-German - translation. A model ID overrides the `source` and `target` parameters and - is required if you use a custom model. If no model ID is specified, you - must specify at least a target language. - :param str source: (optional) Language code that specifies the language of - the source document. If omitted, the service derives the source language - from the input text. The input must contain sufficient text for the service - to identify the language reliably. - :param str target: (optional) Language code that specifies the target - language for translation. Required if model ID is not specified. - :param str document_id: (optional) To use a previously submitted document - as the source for a new translation, enter the `document_id` of the - document. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object - """ - - if file is None: - raise ValueError('file must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='translate_document', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - form_data = [] - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if model_id: - form_data.append(('model_id', (None, model_id, 'text/plain'))) - if source: - form_data.append(('source', (None, source, 'text/plain'))) - if target: - form_data.append(('target', (None, target, 'text/plain'))) - if document_id: - form_data.append(('document_id', (None, document_id, 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/documents' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - ) - - response = self.send(request, **kwargs) - return response - - def get_document_status( - self, - document_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get document status. - - Gets the translation status of a document. - - :param str document_id: The document ID of the document. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object - """ - - if not document_id: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_document_status', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['document_id'] - path_param_values = self.encode_path_vars(document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/documents/{document_id}'.format(**path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def delete_document( - self, - document_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete document. - - Deletes a document. - - :param str document_id: Document ID of the document to delete. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not document_id: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_document', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['document_id'] - path_param_values = self.encode_path_vars(document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/documents/{document_id}'.format(**path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_translated_document( - self, - document_id: str, - *, - accept: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Get translated document. - - Gets the translated document associated with the given document ID. - - :param str document_id: The document ID of the document that was submitted - for translation. - :param str accept: (optional) The type of the response: - application/powerpoint, application/mspowerpoint, application/x-rtf, - application/json, application/xml, application/vnd.ms-excel, - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, - application/vnd.ms-powerpoint, - application/vnd.openxmlformats-officedocument.presentationml.presentation, - application/msword, - application/vnd.openxmlformats-officedocument.wordprocessingml.document, - application/vnd.oasis.opendocument.spreadsheet, - application/vnd.oasis.opendocument.presentation, - application/vnd.oasis.opendocument.text, application/pdf, application/rtf, - text/html, text/json, text/plain, text/richtext, text/rtf, or text/xml. A - character encoding can be specified by including a `charset` parameter. For - example, 'text/html;charset=utf-8'. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `BinaryIO` result - """ - - if not document_id: - raise ValueError('document_id must be provided') - headers = { - 'Accept': accept, - } - 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, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['document_id'] - path_param_values = self.encode_path_vars(document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/documents/{document_id}/translated_document'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - -class CreateModelEnums: - """ - Enums for create_model parameters. - """ - - class ForcedGlossaryContentType(str, Enum): - """ - The content type of forced_glossary. - """ - - APPLICATION_X_TMX_XML = 'application/x-tmx+xml' - APPLICATION_XLIFF_XML = 'application/xliff+xml' - TEXT_CSV = 'text/csv' - TEXT_TAB_SEPARATED_VALUES = 'text/tab-separated-values' - APPLICATION_JSON = 'application/json' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' - - class ParallelCorpusContentType(str, Enum): - """ - The content type of parallel_corpus. - """ - - APPLICATION_X_TMX_XML = 'application/x-tmx+xml' - APPLICATION_XLIFF_XML = 'application/xliff+xml' - TEXT_CSV = 'text/csv' - TEXT_TAB_SEPARATED_VALUES = 'text/tab-separated-values' - APPLICATION_JSON = 'application/json' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' - - -class TranslateDocumentEnums: - """ - Enums for translate_document parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - - APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_OCTET_STREAM = 'application/octet-stream' - APPLICATION_PDF = 'application/pdf' - APPLICATION_POWERPOINT = 'application/powerpoint' - APPLICATION_RTF = 'application/rtf' - APPLICATION_TTAF_XML = 'application/ttaf+xml' - APPLICATION_TTML_XML = 'application/ttml+xml' - APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' - APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' - APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' - APPLICATION_VND_MS_EXCEL = 'application/vnd.ms-excel' - APPLICATION_VND_MS_POWERPOINT = 'application/vnd.ms-powerpoint' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = 'application/vnd.openxmlformats-officedocument.presentationml.presentation' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_X_RTF = 'application/x-rtf' - APPLICATION_XHTML_XML = 'application/xhtml+xml' - APPLICATION_XML = 'application/xml' - TEXT_HTML = 'text/html' - TEXT_JSON = 'text/json' - TEXT_PLAIN = 'text/plain' - TEXT_RICHTEXT = 'text/richtext' - TEXT_RTF = 'text/rtf' - TEXT_SBV = 'text/sbv' - TEXT_SRT = 'text/srt' - TEXT_XML = 'text/xml' - - -class GetTranslatedDocumentEnums: - """ - Enums for get_translated_document parameters. - """ - - class Accept(str, Enum): - """ - The type of the response: application/powerpoint, application/mspowerpoint, - application/x-rtf, application/json, application/xml, application/vnd.ms-excel, - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, - application/vnd.ms-powerpoint, - application/vnd.openxmlformats-officedocument.presentationml.presentation, - application/msword, - application/vnd.openxmlformats-officedocument.wordprocessingml.document, - application/vnd.oasis.opendocument.spreadsheet, - application/vnd.oasis.opendocument.presentation, - application/vnd.oasis.opendocument.text, application/pdf, application/rtf, - text/html, text/json, text/plain, text/richtext, text/rtf, or text/xml. A - character encoding can be specified by including a `charset` parameter. For - example, 'text/html;charset=utf-8'. - """ - - APPLICATION_POWERPOINT = 'application/powerpoint' - APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' - APPLICATION_X_RTF = 'application/x-rtf' - APPLICATION_JSON = 'application/json' - APPLICATION_XML = 'application/xml' - APPLICATION_VND_MS_EXCEL = 'application/vnd.ms-excel' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' - APPLICATION_VND_MS_POWERPOINT = 'application/vnd.ms-powerpoint' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = 'application/vnd.openxmlformats-officedocument.presentationml.presentation' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' - APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' - APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' - APPLICATION_PDF = 'application/pdf' - APPLICATION_RTF = 'application/rtf' - TEXT_HTML = 'text/html' - TEXT_JSON = 'text/json' - TEXT_PLAIN = 'text/plain' - TEXT_RICHTEXT = 'text/richtext' - TEXT_RTF = 'text/rtf' - TEXT_XML = 'text/xml' - - -############################################################################## -# Models -############################################################################## - - -class DeleteModelResult: - """ - DeleteModelResult. - - :param str status: "OK" indicates that the model was successfully deleted. - """ - - def __init__( - self, - status: str, - ) -> None: - """ - Initialize a DeleteModelResult object. - - :param str status: "OK" indicates that the model was successfully deleted. - """ - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteModelResult': - """Initialize a DeleteModelResult object from a json dictionary.""" - args = {} - if (status := _dict.get('status')) is not None: - args['status'] = status - else: - raise ValueError( - 'Required property \'status\' not present in DeleteModelResult JSON' - ) - return cls(**args) - - @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 _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: '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: 'DeleteModelResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentList: - """ - DocumentList. - - :param List[DocumentStatus] documents: An array of all previously submitted - documents. - """ - - def __init__( - self, - documents: List['DocumentStatus'], - ) -> None: - """ - Initialize a DocumentList object. - - :param List[DocumentStatus] documents: An array of all previously submitted - documents. - """ - self.documents = documents - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentList': - """Initialize a DocumentList object from a json dictionary.""" - args = {} - if (documents := _dict.get('documents')) is not None: - args['documents'] = [DocumentStatus.from_dict(v) for v in documents] - else: - raise ValueError( - 'Required property \'documents\' not present in DocumentList JSON' - ) - return cls(**args) - - @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: - documents_list = [] - for v in self.documents: - if isinstance(v, dict): - documents_list.append(v) - else: - documents_list.append(v.to_dict()) - _dict['documents'] = documents_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this DocumentList object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'DocumentList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentStatus: - """ - Document information, including translation status. - - :param str document_id: System generated ID identifying a document being - translated using one specific translation model. - :param str filename: filename from the submission (if it was missing in the - multipart-form, 'noname.' is used. - :param str status: The status of the translation job associated with a submitted - document. - :param str model_id: A globally unique string that identifies the underlying - model that is used for translation. - :param str base_model_id: (optional) Model ID of the base model that was used to - customize the model. If the model is not a custom model, this will be absent or - an empty string. - :param str source: Translation source language code. - :param float detected_language_confidence: (optional) A score between 0 and 1 - indicating the confidence of source language detection. A higher value indicates - greater confidence. This is returned only when the service automatically detects - the source language. - :param str target: Translation target language code. - :param datetime created: The time when the document was submitted. - :param datetime completed: (optional) The time when the translation completed. - :param int word_count: (optional) An estimate of the number of words in the - source document. Returned only if `status` is `available`. - :param int character_count: (optional) The number of characters in the source - document, present only if status=available. - """ - - def __init__( - self, - document_id: str, - filename: str, - status: str, - model_id: str, - source: str, - target: str, - created: datetime, - *, - base_model_id: Optional[str] = None, - detected_language_confidence: Optional[float] = None, - completed: Optional[datetime] = None, - word_count: Optional[int] = None, - character_count: Optional[int] = None, - ) -> None: - """ - Initialize a DocumentStatus object. - - :param str document_id: System generated ID identifying a document being - translated using one specific translation model. - :param str filename: filename from the submission (if it was missing in the - multipart-form, 'noname.' is used. - :param str status: The status of the translation job associated with a - submitted document. - :param str model_id: A globally unique string that identifies the - underlying model that is used for translation. - :param str source: Translation source language code. - :param str target: Translation target language code. - :param datetime created: The time when the document was submitted. - :param str base_model_id: (optional) Model ID of the base model that was - used to customize the model. If the model is not a custom model, this will - be absent or an empty string. - :param float detected_language_confidence: (optional) A score between 0 and - 1 indicating the confidence of source language detection. A higher value - indicates greater confidence. This is returned only when the service - automatically detects the source language. - :param datetime completed: (optional) The time when the translation - completed. - :param int word_count: (optional) An estimate of the number of words in the - source document. Returned only if `status` is `available`. - :param int character_count: (optional) The number of characters in the - source document, present only if status=available. - """ - self.document_id = document_id - self.filename = filename - self.status = status - self.model_id = model_id - self.base_model_id = base_model_id - self.source = source - self.detected_language_confidence = detected_language_confidence - self.target = target - self.created = created - self.completed = completed - self.word_count = word_count - self.character_count = character_count - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentStatus': - """Initialize a DocumentStatus object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - else: - raise ValueError( - 'Required property \'document_id\' not present in DocumentStatus JSON' - ) - if (filename := _dict.get('filename')) is not None: - args['filename'] = filename - else: - raise ValueError( - 'Required property \'filename\' not present in DocumentStatus JSON' - ) - if (status := _dict.get('status')) is not None: - args['status'] = status - else: - raise ValueError( - 'Required property \'status\' not present in DocumentStatus JSON' - ) - if (model_id := _dict.get('model_id')) is not None: - args['model_id'] = model_id - else: - raise ValueError( - 'Required property \'model_id\' not present in DocumentStatus JSON' - ) - if (base_model_id := _dict.get('base_model_id')) is not None: - args['base_model_id'] = base_model_id - if (source := _dict.get('source')) is not None: - args['source'] = source - else: - raise ValueError( - 'Required property \'source\' not present in DocumentStatus JSON' - ) - if (detected_language_confidence := - _dict.get('detected_language_confidence')) is not None: - args['detected_language_confidence'] = detected_language_confidence - if (target := _dict.get('target')) is not None: - args['target'] = target - else: - raise ValueError( - 'Required property \'target\' not present in DocumentStatus JSON' - ) - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - else: - raise ValueError( - 'Required property \'created\' not present in DocumentStatus JSON' - ) - if (completed := _dict.get('completed')) is not None: - args['completed'] = string_to_datetime(completed) - if (word_count := _dict.get('word_count')) is not None: - args['word_count'] = word_count - if (character_count := _dict.get('character_count')) is not None: - args['character_count'] = character_count - return cls(**args) - - @classmethod - 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: - _dict['document_id'] = self.document_id - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'base_model_id') and self.base_model_id is not None: - _dict['base_model_id'] = self.base_model_id - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'detected_language_confidence' - ) and self.detected_language_confidence is not None: - _dict[ - 'detected_language_confidence'] = self.detected_language_confidence - if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'completed') and self.completed is not None: - _dict['completed'] = datetime_to_string(self.completed) - if hasattr(self, 'word_count') and self.word_count is not None: - _dict['word_count'] = self.word_count - if hasattr(self, - 'character_count') and self.character_count is not None: - _dict['character_count'] = self.character_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 DocumentStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'DocumentStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the translation job associated with a submitted document. - """ - - PROCESSING = 'processing' - AVAILABLE = 'available' - FAILED = 'failed' - - -class IdentifiableLanguage: - """ - IdentifiableLanguage. - - :param str language: The language code for an identifiable language. - :param str name: The name of the identifiable language. - """ - - def __init__( - self, - language: str, - name: str, - ) -> None: - """ - Initialize a IdentifiableLanguage object. - - :param str language: The language code for an identifiable language. - :param str name: The name of the identifiable language. - """ - self.language = language - self.name = name - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguage': - """Initialize a IdentifiableLanguage object from a json dictionary.""" - args = {} - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in IdentifiableLanguage JSON' - ) - if (name := _dict.get('name')) is not None: - args['name'] = name - else: - raise ValueError( - 'Required property \'name\' not present in IdentifiableLanguage JSON' - ) - return cls(**args) - - @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: - _dict['language'] = self.language - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - 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 IdentifiableLanguage object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'IdentifiableLanguage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IdentifiableLanguages: - """ - IdentifiableLanguages. - - :param List[IdentifiableLanguage] languages: A list of all languages that the - service can identify. - """ - - def __init__( - self, - languages: List['IdentifiableLanguage'], - ) -> None: - """ - Initialize a IdentifiableLanguages object. - - :param List[IdentifiableLanguage] languages: A list of all languages that - the service can identify. - """ - self.languages = languages - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguages': - """Initialize a IdentifiableLanguages object from a json dictionary.""" - args = {} - if (languages := _dict.get('languages')) is not None: - args['languages'] = [ - IdentifiableLanguage.from_dict(v) for v in languages - ] - else: - raise ValueError( - 'Required property \'languages\' not present in IdentifiableLanguages JSON' - ) - return cls(**args) - - @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: - languages_list = [] - for v in self.languages: - if isinstance(v, dict): - languages_list.append(v) - else: - languages_list.append(v.to_dict()) - _dict['languages'] = languages_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this IdentifiableLanguages object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'IdentifiableLanguages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IdentifiedLanguage: - """ - IdentifiedLanguage. - - :param str language: The language code for an identified language. - :param float confidence: The confidence score for the identified language. - """ - - def __init__( - self, - language: str, - confidence: float, - ) -> None: - """ - Initialize a IdentifiedLanguage object. - - :param str language: The language code for an identified language. - :param float confidence: The confidence score for the identified language. - """ - self.language = language - self.confidence = confidence - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguage': - """Initialize a IdentifiedLanguage object from a json dictionary.""" - args = {} - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in IdentifiedLanguage JSON' - ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - else: - raise ValueError( - 'Required property \'confidence\' not present in IdentifiedLanguage JSON' - ) - return cls(**args) - - @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: - _dict['language'] = self.language - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - 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 IdentifiedLanguage object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'IdentifiedLanguage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IdentifiedLanguages: - """ - IdentifiedLanguages. - - :param List[IdentifiedLanguage] languages: A ranking of identified languages - with confidence scores. - """ - - def __init__( - self, - languages: List['IdentifiedLanguage'], - ) -> None: - """ - Initialize a IdentifiedLanguages object. - - :param List[IdentifiedLanguage] languages: A ranking of identified - languages with confidence scores. - """ - self.languages = languages - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguages': - """Initialize a IdentifiedLanguages object from a json dictionary.""" - args = {} - if (languages := _dict.get('languages')) is not None: - args['languages'] = [ - IdentifiedLanguage.from_dict(v) for v in languages - ] - else: - raise ValueError( - 'Required property \'languages\' not present in IdentifiedLanguages JSON' - ) - return cls(**args) - - @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: - languages_list = [] - for v in self.languages: - if isinstance(v, dict): - languages_list.append(v) - else: - languages_list.append(v.to_dict()) - _dict['languages'] = languages_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this IdentifiedLanguages object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'IdentifiedLanguages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Language: - """ - Response payload for languages. - - :param str language: (optional) The language code for the language (for example, - `af`). - :param str language_name: (optional) The name of the language in English (for - example, `Afrikaans`). - :param str native_language_name: (optional) The native name of the language (for - example, `Afrikaans`). - :param str country_code: (optional) The country code for the language (for - example, `ZA` for South Africa). - :param bool words_separated: (optional) Indicates whether words of the language - are separated by whitespace: `true` if the words are separated; `false` - otherwise. - :param str direction: (optional) Indicates the direction of the language: - `right_to_left` or `left_to_right`. - :param bool supported_as_source: (optional) Indicates whether the language can - be used as the source for translation: `true` if the language can be used as the - source; `false` otherwise. - :param bool supported_as_target: (optional) Indicates whether the language can - be used as the target for translation: `true` if the language can be used as the - target; `false` otherwise. - :param bool identifiable: (optional) Indicates whether the language supports - automatic detection: `true` if the language can be detected automatically; - `false` otherwise. - """ - - def __init__( - self, - *, - language: Optional[str] = None, - language_name: Optional[str] = None, - native_language_name: Optional[str] = None, - country_code: Optional[str] = None, - words_separated: Optional[bool] = None, - direction: Optional[str] = None, - supported_as_source: Optional[bool] = None, - supported_as_target: Optional[bool] = None, - identifiable: Optional[bool] = None, - ) -> None: - """ - Initialize a Language object. - - :param str language: (optional) The language code for the language (for - example, `af`). - :param str language_name: (optional) The name of the language in English - (for example, `Afrikaans`). - :param str native_language_name: (optional) The native name of the language - (for example, `Afrikaans`). - :param str country_code: (optional) The country code for the language (for - example, `ZA` for South Africa). - :param bool words_separated: (optional) Indicates whether words of the - language are separated by whitespace: `true` if the words are separated; - `false` otherwise. - :param str direction: (optional) Indicates the direction of the language: - `right_to_left` or `left_to_right`. - :param bool supported_as_source: (optional) Indicates whether the language - can be used as the source for translation: `true` if the language can be - used as the source; `false` otherwise. - :param bool supported_as_target: (optional) Indicates whether the language - can be used as the target for translation: `true` if the language can be - used as the target; `false` otherwise. - :param bool identifiable: (optional) Indicates whether the language - supports automatic detection: `true` if the language can be detected - automatically; `false` otherwise. - """ - self.language = language - self.language_name = language_name - self.native_language_name = native_language_name - self.country_code = country_code - self.words_separated = words_separated - self.direction = direction - self.supported_as_source = supported_as_source - self.supported_as_target = supported_as_target - self.identifiable = identifiable - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Language': - """Initialize a Language object from a json dictionary.""" - args = {} - if (language := _dict.get('language')) is not None: - args['language'] = language - if (language_name := _dict.get('language_name')) is not None: - args['language_name'] = language_name - if (native_language_name := - _dict.get('native_language_name')) is not None: - args['native_language_name'] = native_language_name - if (country_code := _dict.get('country_code')) is not None: - args['country_code'] = country_code - if (words_separated := _dict.get('words_separated')) is not None: - args['words_separated'] = words_separated - if (direction := _dict.get('direction')) is not None: - args['direction'] = direction - if (supported_as_source := - _dict.get('supported_as_source')) is not None: - args['supported_as_source'] = supported_as_source - if (supported_as_target := - _dict.get('supported_as_target')) is not None: - args['supported_as_target'] = supported_as_target - if (identifiable := _dict.get('identifiable')) is not None: - args['identifiable'] = identifiable - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Language object from 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: - _dict['language'] = self.language - if hasattr(self, 'language_name') and self.language_name is not None: - _dict['language_name'] = self.language_name - if hasattr(self, 'native_language_name' - ) and self.native_language_name is not None: - _dict['native_language_name'] = self.native_language_name - if hasattr(self, 'country_code') and self.country_code is not None: - _dict['country_code'] = self.country_code - if hasattr(self, - 'words_separated') and self.words_separated is not None: - _dict['words_separated'] = self.words_separated - if hasattr(self, 'direction') and self.direction is not None: - _dict['direction'] = self.direction - if hasattr( - self, - 'supported_as_source') and self.supported_as_source is not None: - _dict['supported_as_source'] = self.supported_as_source - if hasattr( - self, - 'supported_as_target') and self.supported_as_target is not None: - _dict['supported_as_target'] = self.supported_as_target - if hasattr(self, 'identifiable') and self.identifiable is not None: - _dict['identifiable'] = self.identifiable - 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 Language object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Language') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Language') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Languages: - """ - The response type for listing supported languages. - - :param List[Language] languages: An array of supported languages with - information about each language. - """ - - def __init__( - self, - languages: List['Language'], - ) -> None: - """ - Initialize a Languages object. - - :param List[Language] languages: An array of supported languages with - information about each language. - """ - self.languages = languages - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Languages': - """Initialize a Languages object from a json dictionary.""" - args = {} - if (languages := _dict.get('languages')) is not None: - args['languages'] = [Language.from_dict(v) for v in languages] - else: - raise ValueError( - 'Required property \'languages\' not present in Languages JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Languages object from 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: - languages_list = [] - for v in self.languages: - if isinstance(v, dict): - languages_list.append(v) - else: - languages_list.append(v.to_dict()) - _dict['languages'] = languages_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this Languages object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Languages') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'Languages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Translation: - """ - Translation. - - :param str translation: Translation output in UTF-8. - """ - - def __init__( - self, - translation: str, - ) -> None: - """ - Initialize a Translation object. - - :param str translation: Translation output in UTF-8. - """ - self.translation = translation - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Translation': - """Initialize a Translation object from a json dictionary.""" - args = {} - if (translation := _dict.get('translation')) is not None: - args['translation'] = translation - else: - raise ValueError( - 'Required property \'translation\' not present in Translation JSON' - ) - return cls(**args) - - @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 _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: '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: 'Translation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TranslationModel: - """ - Response payload for models. - - :param str model_id: A globally unique string that identifies the underlying - model that is used for translation. - :param str name: (optional) Optional name that can be specified when the model - is created. - :param str source: (optional) Translation source language code. - :param str target: (optional) Translation target language code. - :param str base_model_id: (optional) Model ID of the base model that was used to - customize the model. If the model is not a custom model, this will be an empty - string. - :param str domain: (optional) The domain of the translation model. - :param bool customizable: (optional) Whether this model can be used as a base - for customization. Customized models are not further customizable, and some base - models are not customizable. - :param bool default_model: (optional) Whether or not the model is a default - model. A default model is the model for a given language pair that will be used - when that language pair is specified in the source and target parameters. - :param str owner: (optional) Either an empty string, indicating the model is not - a custom model, or the ID of the service instance that created the model. - :param str status: (optional) Availability of a model. - """ - - def __init__( - self, - model_id: str, - *, - name: Optional[str] = None, - source: Optional[str] = None, - target: Optional[str] = None, - base_model_id: Optional[str] = None, - domain: Optional[str] = None, - customizable: Optional[bool] = None, - default_model: Optional[bool] = None, - owner: Optional[str] = None, - status: Optional[str] = None, - ) -> None: - """ - Initialize a TranslationModel object. - - :param str model_id: A globally unique string that identifies the - underlying model that is used for translation. - :param str name: (optional) Optional name that can be specified when the - model is created. - :param str source: (optional) Translation source language code. - :param str target: (optional) Translation target language code. - :param str base_model_id: (optional) Model ID of the base model that was - used to customize the model. If the model is not a custom model, this will - be an empty string. - :param str domain: (optional) The domain of the translation model. - :param bool customizable: (optional) Whether this model can be used as a - base for customization. Customized models are not further customizable, and - some base models are not customizable. - :param bool default_model: (optional) Whether or not the model is a default - model. A default model is the model for a given language pair that will be - used when that language pair is specified in the source and target - parameters. - :param str owner: (optional) Either an empty string, indicating the model - is not a custom model, or the ID of the service instance that created the - model. - :param str status: (optional) Availability of a model. - """ - self.model_id = model_id - self.name = name - self.source = source - self.target = target - self.base_model_id = base_model_id - self.domain = domain - self.customizable = customizable - self.default_model = default_model - self.owner = owner - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TranslationModel': - """Initialize a TranslationModel object from a json dictionary.""" - args = {} - if (model_id := _dict.get('model_id')) is not None: - args['model_id'] = model_id - else: - raise ValueError( - 'Required property \'model_id\' not present in TranslationModel JSON' - ) - if (name := _dict.get('name')) is not None: - args['name'] = name - if (source := _dict.get('source')) is not None: - args['source'] = source - if (target := _dict.get('target')) is not None: - args['target'] = target - if (base_model_id := _dict.get('base_model_id')) is not None: - args['base_model_id'] = base_model_id - if (domain := _dict.get('domain')) is not None: - args['domain'] = domain - if (customizable := _dict.get('customizable')) is not None: - args['customizable'] = customizable - if (default_model := _dict.get('default_model')) is not None: - args['default_model'] = default_model - if (owner := _dict.get('owner')) is not None: - args['owner'] = owner - if (status := _dict.get('status')) is not None: - args['status'] = status - return cls(**args) - - @classmethod - 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: - _dict['model_id'] = self.model_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target - if hasattr(self, 'base_model_id') and self.base_model_id is not None: - _dict['base_model_id'] = self.base_model_id - if hasattr(self, 'domain') and self.domain is not None: - _dict['domain'] = self.domain - if hasattr(self, 'customizable') and self.customizable is not None: - _dict['customizable'] = self.customizable - if hasattr(self, 'default_model') and self.default_model is not None: - _dict['default_model'] = self.default_model - if hasattr(self, 'owner') and self.owner is not None: - _dict['owner'] = self.owner - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 TranslationModel object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'TranslationModel') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Availability of a model. - """ - - UPLOADING = 'uploading' - UPLOADED = 'uploaded' - DISPATCHING = 'dispatching' - QUEUED = 'queued' - TRAINING = 'training' - TRAINED = 'trained' - PUBLISHING = 'publishing' - AVAILABLE = 'available' - DELETED = 'deleted' - ERROR = 'error' - - -class TranslationModels: - """ - The response type for listing existing translation models. - - :param List[TranslationModel] models: An array of available models. - """ - - def __init__( - self, - models: List['TranslationModel'], - ) -> None: - """ - Initialize a TranslationModels object. - - :param List[TranslationModel] models: An array of available models. - """ - self.models = models - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TranslationModels': - """Initialize a TranslationModels object from a json dictionary.""" - args = {} - if (models := _dict.get('models')) is not None: - args['models'] = [TranslationModel.from_dict(v) for v in models] - else: - raise ValueError( - 'Required property \'models\' not present in TranslationModels JSON' - ) - return cls(**args) - - @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: - models_list = [] - for v in self.models: - if isinstance(v, dict): - models_list.append(v) - else: - models_list.append(v.to_dict()) - _dict['models'] = models_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TranslationModels object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'TranslationModels') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TranslationResult: - """ - TranslationResult. - - :param int word_count: An estimate of the number of words in the input text. - :param int character_count: Number of characters in the input text. - :param str detected_language: (optional) The language code of the source text if - the source language was automatically detected. - :param float detected_language_confidence: (optional) A score between 0 and 1 - indicating the confidence of source language detection. A higher value indicates - greater confidence. This is returned only when the service automatically detects - the source language. - :param List[Translation] translations: List of translation output in UTF-8, - corresponding to the input text entries. - """ - - def __init__( - self, - word_count: int, - character_count: int, - translations: List['Translation'], - *, - detected_language: Optional[str] = None, - detected_language_confidence: Optional[float] = None, - ) -> None: - """ - Initialize a TranslationResult object. - - :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, - corresponding to the input text entries. - :param str detected_language: (optional) The language code of the source - text if the source language was automatically detected. - :param float detected_language_confidence: (optional) A score between 0 and - 1 indicating the confidence of source language detection. A higher value - indicates greater confidence. This is returned only when the service - automatically detects the source language. - """ - self.word_count = word_count - self.character_count = character_count - self.detected_language = detected_language - self.detected_language_confidence = detected_language_confidence - self.translations = translations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TranslationResult': - """Initialize a TranslationResult object from a json dictionary.""" - args = {} - if (word_count := _dict.get('word_count')) is not None: - args['word_count'] = word_count - else: - raise ValueError( - 'Required property \'word_count\' not present in TranslationResult JSON' - ) - if (character_count := _dict.get('character_count')) is not None: - args['character_count'] = character_count - else: - raise ValueError( - 'Required property \'character_count\' not present in TranslationResult JSON' - ) - if (detected_language := _dict.get('detected_language')) is not None: - args['detected_language'] = detected_language - if (detected_language_confidence := - _dict.get('detected_language_confidence')) is not None: - args['detected_language_confidence'] = detected_language_confidence - if (translations := _dict.get('translations')) is not None: - args['translations'] = [ - Translation.from_dict(v) for v in translations - ] - else: - raise ValueError( - 'Required property \'translations\' not present in TranslationResult JSON' - ) - return cls(**args) - - @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: - _dict['word_count'] = self.word_count - if hasattr(self, - 'character_count') and self.character_count is not None: - _dict['character_count'] = self.character_count - if hasattr(self, - 'detected_language') and self.detected_language is not None: - _dict['detected_language'] = self.detected_language - if hasattr(self, 'detected_language_confidence' - ) and self.detected_language_confidence is not None: - _dict[ - 'detected_language_confidence'] = self.detected_language_confidence - if hasattr(self, 'translations') and self.translations is not None: - translations_list = [] - for v in self.translations: - if isinstance(v, dict): - translations_list.append(v) - else: - translations_list.append(v.to_dict()) - _dict['translations'] = translations_list - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __str__(self) -> str: - """Return a `str` version of this TranslationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - 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: 'TranslationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other diff --git a/setup.py b/setup.py index e34bb44b..3e639723 100644 --- a/setup.py +++ b/setup.py @@ -36,13 +36,13 @@ long_description_content_type='text/markdown', url='https://github.com/watson-developer-cloud/python-sdk', include_package_data=True, - keywords='language, vision, question and answer' + - ' tone_analyzer, natural language classifier,' + - ' text to speech, language translation, ' + + keywords='language, question and answer,' + + ' tone_analyzer,' + + ' text to speech,' + 'language identification, concept expansion, machine translation, ' + - 'personality insights, message resonance, watson developer cloud, ' + + 'message resonance, watson developer cloud, ' + ' wdc, watson, ibm, dialog, user modeling,' + - 'tone analyzer, speech to text, visual recognition', + 'speech to text', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', diff --git a/test/integration/test_language_translator_v3.py b/test/integration/test_language_translator_v3.py deleted file mode 100644 index 1fcfd057..00000000 --- a/test/integration/test_language_translator_v3.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding: utf-8 -import unittest -import ibm_watson -from os.path import join, dirname -import pytest -import os - - -@pytest.mark.skipif(os.getenv('LANGUAGE_TRANSLATOR_APIKEY') is None, - reason='requires LANGUAGE_TRANSLATOR_APIKEY') -class TestIntegrationLanguageTranslatorV3(unittest.TestCase): - - @classmethod - def setup_class(cls): - cls.language_translator = ibm_watson.LanguageTranslatorV3('2018-05-01') - cls.language_translator.set_default_headers({'X-Watson-Test': '1'}) - - def test_translate(self): - translation = self.language_translator.translate( - text='Hello', model_id='en-es').get_result() - assert translation is not None - translation = self.language_translator.translate( - text='Hello, how are you?', target='es').get_result() - assert translation is not None - - def test_list_languages(self): - languages = self.language_translator.list_languages() - assert languages is not None - - def test_document_translation(self): - with open(join(dirname(__file__), '../../resources/hello_world.txt'), - 'r') as fileinfo: - translation = self.language_translator.translate_document( - file=fileinfo, file_content_type='text/plain', - model_id='en-es').get_result() - document_id = translation.get('document_id') - assert document_id is not None - - document_status = self.language_translator.get_document_status( - document_id).get_result() - assert document_status is not None - - if document_status.get('status') == 'available': - response = self.language_translator.get_translated_document( - document_id, 'text/plain').get_result() - assert response.content is not None - - list_documents = self.language_translator.list_documents().get_result() - assert list_documents is not None - - delete_document = self.language_translator.delete_document( - document_id).get_result() - assert delete_document is None diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py deleted file mode 100644 index 2fe38ed4..00000000 --- a/test/unit/test_language_translator_v3.py +++ /dev/null @@ -1,1841 +0,0 @@ -# -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2024. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# 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. - -""" -Unit Tests for LanguageTranslatorV3 -""" - -from datetime import datetime, timezone -from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime -import inspect -import io -import json -import pytest -import re -import requests -import responses -import tempfile -import urllib -from ibm_watson.language_translator_v3 import * - -version = '2018-05-01' - -_service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version=version, -) - -_base_url = 'https://api.us-south.language-translator.watson.cloud.ibm.com' -_service.set_service_url(_base_url) - - -def preprocess_url(operation_path: str): - """ - Returns the request url associated with the specified operation path. - This will be base_url concatenated with a quoted version of operation_path. - The returned request URL is used to register the mock response so it needs - to match the request URL that is formed by the requests library. - """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. - request_url = _base_url + operation_path - - # If the request url does NOT end with a /, then just return it as-is. - # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: - return request_url - return re.compile(request_url.rstrip('/') + '/+') - - -############################################################################## -# Start of Service: Languages -############################################################################## -# region - - -class TestListLanguages: - """ - Test Class for list_languages - """ - - @responses.activate - def test_list_languages_all_params(self): - """ - list_languages() - """ - # Set up mock - url = preprocess_url('/v3/languages') - mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.list_languages() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_languages_all_params_with_retries(self): - # Enable retries and run test_list_languages_all_params. - _service.enable_retries() - self.test_list_languages_all_params() - - # Disable retries and run test_list_languages_all_params. - _service.disable_retries() - self.test_list_languages_all_params() - - @responses.activate - def test_list_languages_value_error(self): - """ - test_list_languages_value_error() - """ - # Set up mock - url = preprocess_url('/v3/languages') - mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_languages(**req_copy) - - def test_list_languages_value_error_with_retries(self): - # Enable retries and run test_list_languages_value_error. - _service.enable_retries() - self.test_list_languages_value_error() - - # Disable retries and run test_list_languages_value_error. - _service.disable_retries() - self.test_list_languages_value_error() - - -# endregion -############################################################################## -# End of Service: Languages -############################################################################## - -############################################################################## -# Start of Service: Translation -############################################################################## -# region - - -class TestTranslate: - """ - Test Class for translate - """ - - @responses.activate - def test_translate_all_params(self): - """ - translate() - """ - # Set up mock - url = preprocess_url('/v3/translate') - mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - text = ['testString'] - model_id = 'testString' - source = 'testString' - target = 'testString' - - # Invoke method - response = _service.translate( - text, - model_id=model_id, - source=source, - target=target, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['text'] == ['testString'] - assert req_body['model_id'] == 'testString' - assert req_body['source'] == 'testString' - assert req_body['target'] == 'testString' - - def test_translate_all_params_with_retries(self): - # Enable retries and run test_translate_all_params. - _service.enable_retries() - self.test_translate_all_params() - - # Disable retries and run test_translate_all_params. - _service.disable_retries() - self.test_translate_all_params() - - @responses.activate - def test_translate_value_error(self): - """ - test_translate_value_error() - """ - # Set up mock - url = preprocess_url('/v3/translate') - mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - text = ['testString'] - model_id = 'testString' - source = 'testString' - target = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "text": text, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.translate(**req_copy) - - def test_translate_value_error_with_retries(self): - # Enable retries and run test_translate_value_error. - _service.enable_retries() - self.test_translate_value_error() - - # Disable retries and run test_translate_value_error. - _service.disable_retries() - self.test_translate_value_error() - - -# endregion -############################################################################## -# End of Service: Translation -############################################################################## - -############################################################################## -# Start of Service: Identification -############################################################################## -# region - - -class TestListIdentifiableLanguages: - """ - Test Class for list_identifiable_languages - """ - - @responses.activate - def test_list_identifiable_languages_all_params(self): - """ - list_identifiable_languages() - """ - # Set up mock - url = preprocess_url('/v3/identifiable_languages') - mock_response = '{"languages": [{"language": "language", "name": "name"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.list_identifiable_languages() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_identifiable_languages_all_params_with_retries(self): - # Enable retries and run test_list_identifiable_languages_all_params. - _service.enable_retries() - self.test_list_identifiable_languages_all_params() - - # Disable retries and run test_list_identifiable_languages_all_params. - _service.disable_retries() - self.test_list_identifiable_languages_all_params() - - @responses.activate - def test_list_identifiable_languages_value_error(self): - """ - test_list_identifiable_languages_value_error() - """ - # Set up mock - url = preprocess_url('/v3/identifiable_languages') - mock_response = '{"languages": [{"language": "language", "name": "name"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_identifiable_languages(**req_copy) - - def test_list_identifiable_languages_value_error_with_retries(self): - # Enable retries and run test_list_identifiable_languages_value_error. - _service.enable_retries() - self.test_list_identifiable_languages_value_error() - - # Disable retries and run test_list_identifiable_languages_value_error. - _service.disable_retries() - self.test_list_identifiable_languages_value_error() - - -class TestIdentify: - """ - Test Class for identify - """ - - @responses.activate - def test_identify_all_params(self): - """ - identify() - """ - # Set up mock - url = preprocess_url('/v3/identify') - mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - text = 'testString' - - # Invoke method - response = _service.identify( - text, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - assert str(responses.calls[0].request.body, 'utf-8') == text - - def test_identify_all_params_with_retries(self): - # Enable retries and run test_identify_all_params. - _service.enable_retries() - self.test_identify_all_params() - - # Disable retries and run test_identify_all_params. - _service.disable_retries() - self.test_identify_all_params() - - @responses.activate - def test_identify_value_error(self): - """ - test_identify_value_error() - """ - # Set up mock - url = preprocess_url('/v3/identify') - mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - text = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "text": text, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.identify(**req_copy) - - def test_identify_value_error_with_retries(self): - # Enable retries and run test_identify_value_error. - _service.enable_retries() - self.test_identify_value_error() - - # Disable retries and run test_identify_value_error. - _service.disable_retries() - self.test_identify_value_error() - - -# endregion -############################################################################## -# End of Service: Identification -############################################################################## - -############################################################################## -# Start of Service: Models -############################################################################## -# region - - -class TestListModels: - """ - Test Class for list_models - """ - - @responses.activate - def test_list_models_all_params(self): - """ - list_models() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - source = 'testString' - target = 'testString' - default = True - - # Invoke method - response = _service.list_models( - source=source, - target=target, - default=default, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'source={}'.format(source) in query_string - assert 'target={}'.format(target) in query_string - assert 'default={}'.format('true' if default else 'false') in query_string - - def test_list_models_all_params_with_retries(self): - # Enable retries and run test_list_models_all_params. - _service.enable_retries() - self.test_list_models_all_params() - - # Disable retries and run test_list_models_all_params. - _service.disable_retries() - self.test_list_models_all_params() - - @responses.activate - def test_list_models_required_params(self): - """ - test_list_models_required_params() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.list_models() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_models_required_params_with_retries(self): - # Enable retries and run test_list_models_required_params. - _service.enable_retries() - self.test_list_models_required_params() - - # Disable retries and run test_list_models_required_params. - _service.disable_retries() - self.test_list_models_required_params() - - @responses.activate - def test_list_models_value_error(self): - """ - test_list_models_value_error() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_models(**req_copy) - - def test_list_models_value_error_with_retries(self): - # Enable retries and run test_list_models_value_error. - _service.enable_retries() - self.test_list_models_value_error() - - # Disable retries and run test_list_models_value_error. - _service.disable_retries() - self.test_list_models_value_error() - - -class TestCreateModel: - """ - Test Class for create_model - """ - - @responses.activate - def test_create_model_all_params(self): - """ - create_model() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - base_model_id = 'testString' - forced_glossary = io.BytesIO(b'This is a mock file.').getvalue() - forced_glossary_content_type = 'application/x-tmx+xml' - parallel_corpus = io.BytesIO(b'This is a mock file.').getvalue() - parallel_corpus_content_type = 'application/x-tmx+xml' - name = 'testString' - - # Invoke method - response = _service.create_model( - base_model_id, - forced_glossary=forced_glossary, - forced_glossary_content_type=forced_glossary_content_type, - parallel_corpus=parallel_corpus, - parallel_corpus_content_type=parallel_corpus_content_type, - name=name, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'base_model_id={}'.format(base_model_id) in query_string - assert 'name={}'.format(name) in query_string - - def test_create_model_all_params_with_retries(self): - # Enable retries and run test_create_model_all_params. - _service.enable_retries() - self.test_create_model_all_params() - - # Disable retries and run test_create_model_all_params. - _service.disable_retries() - self.test_create_model_all_params() - - @responses.activate - def test_create_model_required_params(self): - """ - test_create_model_required_params() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - base_model_id = 'testString' - - # Invoke method - response = _service.create_model( - base_model_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'base_model_id={}'.format(base_model_id) in query_string - - def test_create_model_required_params_with_retries(self): - # Enable retries and run test_create_model_required_params. - _service.enable_retries() - self.test_create_model_required_params() - - # Disable retries and run test_create_model_required_params. - _service.disable_retries() - self.test_create_model_required_params() - - @responses.activate - def test_create_model_value_error(self): - """ - test_create_model_value_error() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - base_model_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "base_model_id": base_model_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_model(**req_copy) - - def test_create_model_value_error_with_retries(self): - # Enable retries and run test_create_model_value_error. - _service.enable_retries() - self.test_create_model_value_error() - - # Disable retries and run test_create_model_value_error. - _service.disable_retries() - self.test_create_model_value_error() - - -class TestDeleteModel: - """ - Test Class for delete_model - """ - - @responses.activate - def test_delete_model_all_params(self): - """ - delete_model() - """ - # Set up mock - url = preprocess_url('/v3/models/testString') - mock_response = '{"status": "status"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - model_id = 'testString' - - # Invoke method - response = _service.delete_model( - model_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_model_all_params_with_retries(self): - # Enable retries and run test_delete_model_all_params. - _service.enable_retries() - self.test_delete_model_all_params() - - # Disable retries and run test_delete_model_all_params. - _service.disable_retries() - self.test_delete_model_all_params() - - @responses.activate - def test_delete_model_value_error(self): - """ - test_delete_model_value_error() - """ - # Set up mock - url = preprocess_url('/v3/models/testString') - mock_response = '{"status": "status"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - model_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "model_id": model_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_model(**req_copy) - - def test_delete_model_value_error_with_retries(self): - # Enable retries and run test_delete_model_value_error. - _service.enable_retries() - self.test_delete_model_value_error() - - # Disable retries and run test_delete_model_value_error. - _service.disable_retries() - self.test_delete_model_value_error() - - -class TestGetModel: - """ - Test Class for get_model - """ - - @responses.activate - def test_get_model_all_params(self): - """ - get_model() - """ - # Set up mock - url = preprocess_url('/v3/models/testString') - mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - model_id = 'testString' - - # Invoke method - response = _service.get_model( - model_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_model_all_params_with_retries(self): - # Enable retries and run test_get_model_all_params. - _service.enable_retries() - self.test_get_model_all_params() - - # Disable retries and run test_get_model_all_params. - _service.disable_retries() - self.test_get_model_all_params() - - @responses.activate - def test_get_model_value_error(self): - """ - test_get_model_value_error() - """ - # Set up mock - url = preprocess_url('/v3/models/testString') - mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - model_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "model_id": model_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_model(**req_copy) - - def test_get_model_value_error_with_retries(self): - # Enable retries and run test_get_model_value_error. - _service.enable_retries() - self.test_get_model_value_error() - - # Disable retries and run test_get_model_value_error. - _service.disable_retries() - self.test_get_model_value_error() - - -# endregion -############################################################################## -# End of Service: Models -############################################################################## - -############################################################################## -# Start of Service: DocumentTranslation -############################################################################## -# region - - -class TestListDocuments: - """ - Test Class for list_documents - """ - - @responses.activate - def test_list_documents_all_params(self): - """ - list_documents() - """ - # Set up mock - url = preprocess_url('/v3/documents') - mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.list_documents() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_documents_all_params_with_retries(self): - # Enable retries and run test_list_documents_all_params. - _service.enable_retries() - self.test_list_documents_all_params() - - # Disable retries and run test_list_documents_all_params. - _service.disable_retries() - self.test_list_documents_all_params() - - @responses.activate - def test_list_documents_value_error(self): - """ - test_list_documents_value_error() - """ - # Set up mock - url = preprocess_url('/v3/documents') - mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_documents(**req_copy) - - def test_list_documents_value_error_with_retries(self): - # Enable retries and run test_list_documents_value_error. - _service.enable_retries() - self.test_list_documents_value_error() - - # Disable retries and run test_list_documents_value_error. - _service.disable_retries() - self.test_list_documents_value_error() - - -class TestTranslateDocument: - """ - Test Class for translate_document - """ - - @responses.activate - def test_translate_document_all_params(self): - """ - translate_document() - """ - # Set up mock - url = preprocess_url('/v3/documents') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/mspowerpoint' - model_id = 'testString' - source = 'testString' - target = 'testString' - document_id = 'testString' - - # Invoke method - response = _service.translate_document( - file, - filename=filename, - file_content_type=file_content_type, - model_id=model_id, - source=source, - target=target, - document_id=document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_translate_document_all_params_with_retries(self): - # Enable retries and run test_translate_document_all_params. - _service.enable_retries() - self.test_translate_document_all_params() - - # Disable retries and run test_translate_document_all_params. - _service.disable_retries() - self.test_translate_document_all_params() - - @responses.activate - def test_translate_document_required_params(self): - """ - test_translate_document_required_params() - """ - # Set up mock - url = preprocess_url('/v3/documents') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - - # Invoke method - response = _service.translate_document( - file, - filename=filename, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_translate_document_required_params_with_retries(self): - # Enable retries and run test_translate_document_required_params. - _service.enable_retries() - self.test_translate_document_required_params() - - # Disable retries and run test_translate_document_required_params. - _service.disable_retries() - self.test_translate_document_required_params() - - @responses.activate - def test_translate_document_value_error(self): - """ - test_translate_document_value_error() - """ - # Set up mock - url = preprocess_url('/v3/documents') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "file": file, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.translate_document(**req_copy) - - def test_translate_document_value_error_with_retries(self): - # Enable retries and run test_translate_document_value_error. - _service.enable_retries() - self.test_translate_document_value_error() - - # Disable retries and run test_translate_document_value_error. - _service.disable_retries() - self.test_translate_document_value_error() - - -class TestGetDocumentStatus: - """ - Test Class for get_document_status - """ - - @responses.activate - def test_get_document_status_all_params(self): - """ - get_document_status() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - document_id = 'testString' - - # Invoke method - response = _service.get_document_status( - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_document_status_all_params_with_retries(self): - # Enable retries and run test_get_document_status_all_params. - _service.enable_retries() - self.test_get_document_status_all_params() - - # Disable retries and run test_get_document_status_all_params. - _service.disable_retries() - self.test_get_document_status_all_params() - - @responses.activate - def test_get_document_status_value_error(self): - """ - test_get_document_status_value_error() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_document_status(**req_copy) - - def test_get_document_status_value_error_with_retries(self): - # Enable retries and run test_get_document_status_value_error. - _service.enable_retries() - self.test_get_document_status_value_error() - - # Disable retries and run test_get_document_status_value_error. - _service.disable_retries() - self.test_get_document_status_value_error() - - -class TestDeleteDocument: - """ - Test Class for delete_document - """ - - @responses.activate - def test_delete_document_all_params(self): - """ - delete_document() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - document_id = 'testString' - - # Invoke method - response = _service.delete_document( - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 204 - - def test_delete_document_all_params_with_retries(self): - # Enable retries and run test_delete_document_all_params. - _service.enable_retries() - self.test_delete_document_all_params() - - # Disable retries and run test_delete_document_all_params. - _service.disable_retries() - self.test_delete_document_all_params() - - @responses.activate - def test_delete_document_value_error(self): - """ - test_delete_document_value_error() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_document(**req_copy) - - def test_delete_document_value_error_with_retries(self): - # Enable retries and run test_delete_document_value_error. - _service.enable_retries() - self.test_delete_document_value_error() - - # Disable retries and run test_delete_document_value_error. - _service.disable_retries() - self.test_delete_document_value_error() - - -class TestGetTranslatedDocument: - """ - Test Class for get_translated_document - """ - - @responses.activate - def test_get_translated_document_all_params(self): - """ - get_translated_document() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString/translated_document') - mock_response = 'This is a mock binary response.' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200, - ) - - # Set up parameter values - document_id = 'testString' - accept = 'application/powerpoint' - - # Invoke method - response = _service.get_translated_document( - document_id, - accept=accept, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_translated_document_all_params_with_retries(self): - # Enable retries and run test_get_translated_document_all_params. - _service.enable_retries() - self.test_get_translated_document_all_params() - - # Disable retries and run test_get_translated_document_all_params. - _service.disable_retries() - self.test_get_translated_document_all_params() - - @responses.activate - def test_get_translated_document_required_params(self): - """ - test_get_translated_document_required_params() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString/translated_document') - mock_response = 'This is a mock binary response.' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200, - ) - - # Set up parameter values - document_id = 'testString' - - # Invoke method - response = _service.get_translated_document( - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_translated_document_required_params_with_retries(self): - # Enable retries and run test_get_translated_document_required_params. - _service.enable_retries() - self.test_get_translated_document_required_params() - - # Disable retries and run test_get_translated_document_required_params. - _service.disable_retries() - self.test_get_translated_document_required_params() - - @responses.activate - def test_get_translated_document_value_error(self): - """ - test_get_translated_document_value_error() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString/translated_document') - mock_response = 'This is a mock binary response.' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200, - ) - - # Set up parameter values - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_translated_document(**req_copy) - - def test_get_translated_document_value_error_with_retries(self): - # Enable retries and run test_get_translated_document_value_error. - _service.enable_retries() - self.test_get_translated_document_value_error() - - # Disable retries and run test_get_translated_document_value_error. - _service.disable_retries() - self.test_get_translated_document_value_error() - - -# endregion -############################################################################## -# End of Service: DocumentTranslation -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region - - -class TestModel_DeleteModelResult: - """ - Test Class for DeleteModelResult - """ - - def test_delete_model_result_serialization(self): - """ - Test serialization/deserialization for DeleteModelResult - """ - - # Construct a json representation of a DeleteModelResult model - delete_model_result_model_json = {} - delete_model_result_model_json['status'] = 'testString' - - # Construct a model instance of DeleteModelResult by calling from_dict on the json representation - delete_model_result_model = DeleteModelResult.from_dict(delete_model_result_model_json) - assert delete_model_result_model != False - - # Construct a model instance of DeleteModelResult by calling from_dict on the json representation - delete_model_result_model_dict = DeleteModelResult.from_dict(delete_model_result_model_json).__dict__ - delete_model_result_model2 = DeleteModelResult(**delete_model_result_model_dict) - - # Verify the model instances are equivalent - assert delete_model_result_model == delete_model_result_model2 - - # Convert model instance back to dict and verify no loss of data - delete_model_result_model_json2 = delete_model_result_model.to_dict() - assert delete_model_result_model_json2 == delete_model_result_model_json - - -class TestModel_DocumentList: - """ - Test Class for DocumentList - """ - - def test_document_list_serialization(self): - """ - Test serialization/deserialization for DocumentList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - document_status_model = {} # DocumentStatus - document_status_model['document_id'] = 'testString' - document_status_model['filename'] = 'testString' - document_status_model['status'] = 'processing' - document_status_model['model_id'] = 'testString' - document_status_model['base_model_id'] = 'testString' - document_status_model['source'] = 'testString' - document_status_model['detected_language_confidence'] = 0 - document_status_model['target'] = 'testString' - document_status_model['created'] = '2019-01-01T12:00:00Z' - document_status_model['completed'] = '2019-01-01T12:00:00Z' - document_status_model['word_count'] = 38 - document_status_model['character_count'] = 38 - - # Construct a json representation of a DocumentList model - document_list_model_json = {} - document_list_model_json['documents'] = [document_status_model] - - # Construct a model instance of DocumentList by calling from_dict on the json representation - document_list_model = DocumentList.from_dict(document_list_model_json) - assert document_list_model != False - - # Construct a model instance of DocumentList by calling from_dict on the json representation - document_list_model_dict = DocumentList.from_dict(document_list_model_json).__dict__ - document_list_model2 = DocumentList(**document_list_model_dict) - - # Verify the model instances are equivalent - assert document_list_model == document_list_model2 - - # Convert model instance back to dict and verify no loss of data - document_list_model_json2 = document_list_model.to_dict() - assert document_list_model_json2 == document_list_model_json - - -class TestModel_DocumentStatus: - """ - Test Class for DocumentStatus - """ - - def test_document_status_serialization(self): - """ - Test serialization/deserialization for DocumentStatus - """ - - # Construct a json representation of a DocumentStatus model - document_status_model_json = {} - document_status_model_json['document_id'] = 'testString' - document_status_model_json['filename'] = 'testString' - document_status_model_json['status'] = 'processing' - document_status_model_json['model_id'] = 'testString' - document_status_model_json['base_model_id'] = 'testString' - document_status_model_json['source'] = 'testString' - document_status_model_json['detected_language_confidence'] = 0 - document_status_model_json['target'] = 'testString' - document_status_model_json['created'] = '2019-01-01T12:00:00Z' - document_status_model_json['completed'] = '2019-01-01T12:00:00Z' - document_status_model_json['word_count'] = 38 - document_status_model_json['character_count'] = 38 - - # Construct a model instance of DocumentStatus by calling from_dict on the json representation - document_status_model = DocumentStatus.from_dict(document_status_model_json) - assert document_status_model != False - - # Construct a model instance of DocumentStatus by calling from_dict on the json representation - document_status_model_dict = DocumentStatus.from_dict(document_status_model_json).__dict__ - document_status_model2 = DocumentStatus(**document_status_model_dict) - - # Verify the model instances are equivalent - assert document_status_model == document_status_model2 - - # Convert model instance back to dict and verify no loss of data - document_status_model_json2 = document_status_model.to_dict() - assert document_status_model_json2 == document_status_model_json - - -class TestModel_IdentifiableLanguage: - """ - Test Class for IdentifiableLanguage - """ - - def test_identifiable_language_serialization(self): - """ - Test serialization/deserialization for IdentifiableLanguage - """ - - # Construct a json representation of a IdentifiableLanguage model - identifiable_language_model_json = {} - identifiable_language_model_json['language'] = 'testString' - identifiable_language_model_json['name'] = 'testString' - - # Construct a model instance of IdentifiableLanguage by calling from_dict on the json representation - identifiable_language_model = IdentifiableLanguage.from_dict(identifiable_language_model_json) - assert identifiable_language_model != False - - # Construct a model instance of IdentifiableLanguage by calling from_dict on the json representation - identifiable_language_model_dict = IdentifiableLanguage.from_dict(identifiable_language_model_json).__dict__ - identifiable_language_model2 = IdentifiableLanguage(**identifiable_language_model_dict) - - # Verify the model instances are equivalent - assert identifiable_language_model == identifiable_language_model2 - - # Convert model instance back to dict and verify no loss of data - identifiable_language_model_json2 = identifiable_language_model.to_dict() - assert identifiable_language_model_json2 == identifiable_language_model_json - - -class TestModel_IdentifiableLanguages: - """ - Test Class for IdentifiableLanguages - """ - - def test_identifiable_languages_serialization(self): - """ - Test serialization/deserialization for IdentifiableLanguages - """ - - # Construct dict forms of any model objects needed in order to build this model. - - identifiable_language_model = {} # IdentifiableLanguage - identifiable_language_model['language'] = 'testString' - identifiable_language_model['name'] = 'testString' - - # Construct a json representation of a IdentifiableLanguages model - identifiable_languages_model_json = {} - identifiable_languages_model_json['languages'] = [identifiable_language_model] - - # Construct a model instance of IdentifiableLanguages by calling from_dict on the json representation - identifiable_languages_model = IdentifiableLanguages.from_dict(identifiable_languages_model_json) - assert identifiable_languages_model != False - - # Construct a model instance of IdentifiableLanguages by calling from_dict on the json representation - identifiable_languages_model_dict = IdentifiableLanguages.from_dict(identifiable_languages_model_json).__dict__ - identifiable_languages_model2 = IdentifiableLanguages(**identifiable_languages_model_dict) - - # Verify the model instances are equivalent - assert identifiable_languages_model == identifiable_languages_model2 - - # Convert model instance back to dict and verify no loss of data - identifiable_languages_model_json2 = identifiable_languages_model.to_dict() - assert identifiable_languages_model_json2 == identifiable_languages_model_json - - -class TestModel_IdentifiedLanguage: - """ - Test Class for IdentifiedLanguage - """ - - def test_identified_language_serialization(self): - """ - Test serialization/deserialization for IdentifiedLanguage - """ - - # Construct a json representation of a IdentifiedLanguage model - identified_language_model_json = {} - identified_language_model_json['language'] = 'testString' - identified_language_model_json['confidence'] = 0 - - # Construct a model instance of IdentifiedLanguage by calling from_dict on the json representation - identified_language_model = IdentifiedLanguage.from_dict(identified_language_model_json) - assert identified_language_model != False - - # Construct a model instance of IdentifiedLanguage by calling from_dict on the json representation - identified_language_model_dict = IdentifiedLanguage.from_dict(identified_language_model_json).__dict__ - identified_language_model2 = IdentifiedLanguage(**identified_language_model_dict) - - # Verify the model instances are equivalent - assert identified_language_model == identified_language_model2 - - # Convert model instance back to dict and verify no loss of data - identified_language_model_json2 = identified_language_model.to_dict() - assert identified_language_model_json2 == identified_language_model_json - - -class TestModel_IdentifiedLanguages: - """ - Test Class for IdentifiedLanguages - """ - - def test_identified_languages_serialization(self): - """ - Test serialization/deserialization for IdentifiedLanguages - """ - - # Construct dict forms of any model objects needed in order to build this model. - - identified_language_model = {} # IdentifiedLanguage - identified_language_model['language'] = 'testString' - identified_language_model['confidence'] = 0 - - # Construct a json representation of a IdentifiedLanguages model - identified_languages_model_json = {} - identified_languages_model_json['languages'] = [identified_language_model] - - # Construct a model instance of IdentifiedLanguages by calling from_dict on the json representation - identified_languages_model = IdentifiedLanguages.from_dict(identified_languages_model_json) - assert identified_languages_model != False - - # Construct a model instance of IdentifiedLanguages by calling from_dict on the json representation - identified_languages_model_dict = IdentifiedLanguages.from_dict(identified_languages_model_json).__dict__ - identified_languages_model2 = IdentifiedLanguages(**identified_languages_model_dict) - - # Verify the model instances are equivalent - assert identified_languages_model == identified_languages_model2 - - # Convert model instance back to dict and verify no loss of data - identified_languages_model_json2 = identified_languages_model.to_dict() - assert identified_languages_model_json2 == identified_languages_model_json - - -class TestModel_Language: - """ - Test Class for Language - """ - - def test_language_serialization(self): - """ - Test serialization/deserialization for Language - """ - - # Construct a json representation of a Language model - language_model_json = {} - language_model_json['language'] = 'testString' - language_model_json['language_name'] = 'testString' - language_model_json['native_language_name'] = 'testString' - language_model_json['country_code'] = 'testString' - language_model_json['words_separated'] = True - language_model_json['direction'] = 'testString' - language_model_json['supported_as_source'] = True - language_model_json['supported_as_target'] = True - language_model_json['identifiable'] = True - - # Construct a model instance of Language by calling from_dict on the json representation - language_model = Language.from_dict(language_model_json) - assert language_model != False - - # Construct a model instance of Language by calling from_dict on the json representation - language_model_dict = Language.from_dict(language_model_json).__dict__ - language_model2 = Language(**language_model_dict) - - # Verify the model instances are equivalent - assert language_model == language_model2 - - # Convert model instance back to dict and verify no loss of data - language_model_json2 = language_model.to_dict() - assert language_model_json2 == language_model_json - - -class TestModel_Languages: - """ - Test Class for Languages - """ - - def test_languages_serialization(self): - """ - Test serialization/deserialization for Languages - """ - - # Construct dict forms of any model objects needed in order to build this model. - - language_model = {} # Language - language_model['language'] = 'testString' - language_model['language_name'] = 'testString' - language_model['native_language_name'] = 'testString' - language_model['country_code'] = 'testString' - language_model['words_separated'] = True - language_model['direction'] = 'testString' - language_model['supported_as_source'] = True - language_model['supported_as_target'] = True - language_model['identifiable'] = True - - # Construct a json representation of a Languages model - languages_model_json = {} - languages_model_json['languages'] = [language_model] - - # Construct a model instance of Languages by calling from_dict on the json representation - languages_model = Languages.from_dict(languages_model_json) - assert languages_model != False - - # Construct a model instance of Languages by calling from_dict on the json representation - languages_model_dict = Languages.from_dict(languages_model_json).__dict__ - languages_model2 = Languages(**languages_model_dict) - - # Verify the model instances are equivalent - assert languages_model == languages_model2 - - # Convert model instance back to dict and verify no loss of data - languages_model_json2 = languages_model.to_dict() - assert languages_model_json2 == languages_model_json - - -class TestModel_Translation: - """ - Test Class for Translation - """ - - def test_translation_serialization(self): - """ - Test serialization/deserialization for Translation - """ - - # Construct a json representation of a Translation model - translation_model_json = {} - translation_model_json['translation'] = 'testString' - - # Construct a model instance of Translation by calling from_dict on the json representation - translation_model = Translation.from_dict(translation_model_json) - assert translation_model != False - - # Construct a model instance of Translation by calling from_dict on the json representation - translation_model_dict = Translation.from_dict(translation_model_json).__dict__ - translation_model2 = Translation(**translation_model_dict) - - # Verify the model instances are equivalent - assert translation_model == translation_model2 - - # Convert model instance back to dict and verify no loss of data - translation_model_json2 = translation_model.to_dict() - assert translation_model_json2 == translation_model_json - - -class TestModel_TranslationModel: - """ - Test Class for TranslationModel - """ - - def test_translation_model_serialization(self): - """ - Test serialization/deserialization for TranslationModel - """ - - # Construct a json representation of a TranslationModel model - translation_model_model_json = {} - translation_model_model_json['model_id'] = 'testString' - translation_model_model_json['name'] = 'testString' - translation_model_model_json['source'] = 'testString' - translation_model_model_json['target'] = 'testString' - translation_model_model_json['base_model_id'] = 'testString' - translation_model_model_json['domain'] = 'testString' - translation_model_model_json['customizable'] = True - translation_model_model_json['default_model'] = True - translation_model_model_json['owner'] = 'testString' - translation_model_model_json['status'] = 'uploading' - - # Construct a model instance of TranslationModel by calling from_dict on the json representation - translation_model_model = TranslationModel.from_dict(translation_model_model_json) - assert translation_model_model != False - - # Construct a model instance of TranslationModel by calling from_dict on the json representation - translation_model_model_dict = TranslationModel.from_dict(translation_model_model_json).__dict__ - translation_model_model2 = TranslationModel(**translation_model_model_dict) - - # Verify the model instances are equivalent - assert translation_model_model == translation_model_model2 - - # Convert model instance back to dict and verify no loss of data - translation_model_model_json2 = translation_model_model.to_dict() - assert translation_model_model_json2 == translation_model_model_json - - -class TestModel_TranslationModels: - """ - Test Class for TranslationModels - """ - - def test_translation_models_serialization(self): - """ - Test serialization/deserialization for TranslationModels - """ - - # Construct dict forms of any model objects needed in order to build this model. - - translation_model_model = {} # TranslationModel - translation_model_model['model_id'] = 'testString' - translation_model_model['name'] = 'testString' - translation_model_model['source'] = 'testString' - translation_model_model['target'] = 'testString' - translation_model_model['base_model_id'] = 'testString' - translation_model_model['domain'] = 'testString' - translation_model_model['customizable'] = True - translation_model_model['default_model'] = True - translation_model_model['owner'] = 'testString' - translation_model_model['status'] = 'uploading' - - # Construct a json representation of a TranslationModels model - translation_models_model_json = {} - translation_models_model_json['models'] = [translation_model_model] - - # Construct a model instance of TranslationModels by calling from_dict on the json representation - translation_models_model = TranslationModels.from_dict(translation_models_model_json) - assert translation_models_model != False - - # Construct a model instance of TranslationModels by calling from_dict on the json representation - translation_models_model_dict = TranslationModels.from_dict(translation_models_model_json).__dict__ - translation_models_model2 = TranslationModels(**translation_models_model_dict) - - # Verify the model instances are equivalent - assert translation_models_model == translation_models_model2 - - # Convert model instance back to dict and verify no loss of data - translation_models_model_json2 = translation_models_model.to_dict() - assert translation_models_model_json2 == translation_models_model_json - - -class TestModel_TranslationResult: - """ - Test Class for TranslationResult - """ - - def test_translation_result_serialization(self): - """ - Test serialization/deserialization for TranslationResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - translation_model = {} # Translation - translation_model['translation'] = 'testString' - - # Construct a json representation of a TranslationResult model - translation_result_model_json = {} - translation_result_model_json['word_count'] = 38 - translation_result_model_json['character_count'] = 38 - translation_result_model_json['detected_language'] = 'testString' - translation_result_model_json['detected_language_confidence'] = 0 - translation_result_model_json['translations'] = [translation_model] - - # Construct a model instance of TranslationResult by calling from_dict on the json representation - translation_result_model = TranslationResult.from_dict(translation_result_model_json) - assert translation_result_model != False - - # Construct a model instance of TranslationResult by calling from_dict on the json representation - translation_result_model_dict = TranslationResult.from_dict(translation_result_model_json).__dict__ - translation_result_model2 = TranslationResult(**translation_result_model_dict) - - # Verify the model instances are equivalent - assert translation_result_model == translation_result_model2 - - # Convert model instance back to dict and verify no loss of data - translation_result_model_json2 = translation_result_model.to_dict() - assert translation_result_model_json2 == translation_result_model_json - - -# endregion -############################################################################## -# End of Model Tests -############################################################################## From ed8859a4515a10b0106647b4871160c70df4175f Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 18 Oct 2024 11:57:31 -0500 Subject: [PATCH 07/11] feat(discov2): add functions for new batches api --- ibm_watson/discovery_v2.py | 452 ++++++++++++++++++++++++++++++++- test/unit/test_discovery_v2.py | 415 ++++++++++++++++++++++++++++++ 2 files changed, 856 insertions(+), 11 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index f3ede4e6..e5c0fbe7 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1338,8 +1338,12 @@ def query( (`extracted_metadata.filename`) fields. If this parameter is an empty list, then all fields are returned. :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. + beginning. Consider that the `count` is set to 10 (the default value) and + the total number of results that are returned is 100. In this case, the + following examples show the returned results for different `offset` values: + * If `offset` is set to 95, it returns the last 5 results. + * If `offset` is set to 10, it returns the second batch of 10 results. + * If `offset` is set to 100 or more, it returns empty results. :param 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 @@ -2855,6 +2859,231 @@ def delete_enrichment( response = self.send(request, **kwargs) return response + ######################### + # Batches + ######################### + + def list_batches( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: + """ + List batches. + + A batch is a set of documents that are ready for enrichment by an external + application. After you apply a webhook enrichment to a collection, and then + process or upload documents to the collection, Discovery creates a batch with a + unique **batch_id**. + To start, you must register your external application as a **webhook** type by + using the [Create enrichment API](/apidocs/discovery-data#createenrichment) + method. + Use the List batches API to get the following: + * Notified batches that are not yet pulled by the external enrichment + application. + * Batches that are pulled, but not yet pushed to Discovery by the external + enrichment application. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ListBatchesResponse` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_batches', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/batches'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def pull_batches( + self, + project_id: str, + collection_id: str, + batch_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Pull batches. + + Pull a batch of documents from Discovery for enrichment by an external + application. Ensure to include the `Accept-Encoding: gzip` header in this method + to get the file. You can also implement retry logic when calling this method to + avoid any network errors. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param str batch_id: The Universally Unique Identifier (UUID) of the + document batch that is being requested from Discovery. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `PullBatchesResponse` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if not batch_id: + raise ValueError('batch_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='pull_batches', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id', 'batch_id'] + path_param_values = self.encode_path_vars(project_id, collection_id, + batch_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/batches/{batch_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def push_batches( + self, + project_id: str, + collection_id: str, + batch_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Push batches. + + Push a batch of documents to Discovery after annotation by an external + application. You can implement retry logic when calling this method to avoid any + network errors. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param str batch_id: The Universally Unique Identifier (UUID) of the + document batch that is being requested from Discovery. + :param BinaryIO file: (optional) A compressed newline-delimited JSON + (NDJSON), which is a JSON file with one row of data per line. For example, + `{batch_id}.ndjson.gz`. For more information, see [Binary attachment in the + push batches + method](/docs/discovery-data?topic=discovery-data-external-enrichment#binary-attachment-push-batches). + There is no limitation on the name of the file because Discovery does not + use the name for processing. The list of features in the document is + specified in the `features` object. + :param str filename: (optional) The filename for file. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `bool` result + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if not batch_id: + raise ValueError('batch_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='push_batches', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + form_data = [] + if file: + if not filename and hasattr(file, 'name'): + filename = basename(file.name) + if not filename: + raise ValueError('filename must be provided') + form_data.append( + ('file', (filename, file, 'application/octet-stream'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id', 'batch_id'] + path_param_values = self.encode_path_vars(project_id, collection_id, + batch_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/batches/{batch_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) + + response = self.send(request, **kwargs) + return response + ######################### # Document classifiers ######################### @@ -3974,6 +4203,85 @@ def __ne__(self, other: 'AnalyzedResult') -> bool: return not self == other +class BatchDetails: + """ + A batch is a set of documents that are ready for enrichment by an external + application. After you apply a webhook enrichment to a collection, and then process or + upload documents to the collection, Discovery creates a batch with a unique + **batch_id**. + + :param str batch_id: (optional) The Universally Unique Identifier (UUID) for a + batch of documents. + :param datetime created: (optional) The date and time (RFC3339) that the batch + was created. + :param str enrichment_id: (optional) The Universally Unique Identifier (UUID) + for the external enrichment. + """ + + def __init__( + self, + *, + batch_id: Optional[str] = None, + created: Optional[datetime] = None, + enrichment_id: Optional[str] = None, + ) -> None: + """ + Initialize a BatchDetails object. + + :param str enrichment_id: (optional) The Universally Unique Identifier + (UUID) for the external enrichment. + """ + self.batch_id = batch_id + self.created = created + self.enrichment_id = enrichment_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BatchDetails': + """Initialize a BatchDetails object from a json dictionary.""" + args = {} + if (batch_id := _dict.get('batch_id')) is not None: + args['batch_id'] = batch_id + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BatchDetails object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'batch_id') and getattr(self, 'batch_id') is not None: + _dict['batch_id'] = getattr(self, 'batch_id') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this BatchDetails object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'BatchDetails') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'BatchDetails') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ClassifierFederatedModel: """ An object with details for creating federated document classifier models. @@ -5217,9 +5525,6 @@ class CreateEnrichment: * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. * `webhook`: Connects to an external enrichment application by using a webhook. - The feature is available from IBM Cloud-managed instances only. The external - enrichment feature is beta functionality. Beta features are not supported by the - SDKs. * `sentence_classifier`: Use sentence classifier to classify sentences in your documents. This feature is available in IBM Cloud-managed instances only. The sentence classifier feature is beta functionality. Beta features are not @@ -5262,9 +5567,7 @@ def __init__( * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. * `webhook`: Connects to an external enrichment application by using a - webhook. The feature is available from IBM Cloud-managed instances only. - The external enrichment feature is beta functionality. Beta features are - not supported by the SDKs. + webhook. * `sentence_classifier`: Use sentence classifier to classify sentences in your documents. This feature is available in IBM Cloud-managed instances only. The sentence classifier feature is beta functionality. Beta features @@ -5353,9 +5656,6 @@ class TypeEnum(str, Enum): * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. * `webhook`: Connects to an external enrichment application by using a webhook. - The feature is available from IBM Cloud-managed instances only. The external - enrichment feature is beta functionality. Beta features are not supported by the - SDKs. * `sentence_classifier`: Use sentence classifier to classify sentences in your documents. This feature is available in IBM Cloud-managed instances only. The sentence classifier feature is beta functionality. Beta features are not supported @@ -7560,6 +7860,73 @@ class TypeEnum(str, Enum): BINARY = 'binary' +class ListBatchesResponse: + """ + An object that contains a list of batches that are ready for enrichment by the + external application. + + :param List[BatchDetails] batches: (optional) An array that lists the batches in + a collection. + """ + + def __init__( + self, + *, + batches: Optional[List['BatchDetails']] = None, + ) -> None: + """ + Initialize a ListBatchesResponse object. + + :param List[BatchDetails] batches: (optional) An array that lists the + batches in a collection. + """ + self.batches = batches + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListBatchesResponse': + """Initialize a ListBatchesResponse object from a json dictionary.""" + args = {} + if (batches := _dict.get('batches')) is not None: + args['batches'] = [BatchDetails.from_dict(v) for v in batches] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListBatchesResponse object from 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: + batches_list = [] + for v in self.batches: + if isinstance(v, dict): + batches_list.append(v) + else: + batches_list.append(v.to_dict()) + _dict['batches'] = batches_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ListBatchesResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListBatchesResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ListBatchesResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ListCollectionsResponse: """ Response object that contains an array of collection details. @@ -12747,6 +13114,69 @@ def __ne__(self, other: 'WebhookHeader') -> bool: return not self == other +class PullBatchesResponse: + """ + A compressed newline delimited JSON (NDJSON) file containing the document. The NDJSON + format is used to describe structured data. The file name format is + `{batch_id}.ndjson.gz`. For more information, see [Binary attachment from the pull + batches + method](/docs/discovery-data?topic=discovery-data-external-enrichment#binary-attachment-pull-batches). + + :param str file: (optional) A compressed NDJSON file containing the document. + """ + + def __init__( + self, + *, + file: Optional[str] = None, + ) -> None: + """ + Initialize a PullBatchesResponse object. + + :param str file: (optional) A compressed NDJSON file containing the + document. + """ + self.file = file + + @classmethod + def from_dict(cls, _dict: Dict) -> 'PullBatchesResponse': + """Initialize a PullBatchesResponse object from a json dictionary.""" + args = {} + if (file := _dict.get('file')) is not None: + args['file'] = file + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a PullBatchesResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'file') and self.file is not None: + _dict['file'] = self.file + 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 PullBatchesResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'PullBatchesResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'PullBatchesResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryAggregationQueryCalculationAggregation(QueryAggregation): """ Returns a scalar calculation across all documents for the field specified. Possible diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 4a8bf169..0e172b94 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -4256,6 +4256,326 @@ def test_delete_enrichment_value_error_with_retries(self): # End of Service: Enrichments ############################################################################## +############################################################################## +# Start of Service: Batches +############################################################################## +# region + + +class TestListBatches: + """ + Test Class for list_batches + """ + + @responses.activate + def test_list_batches_all_params(self): + """ + list_batches() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches') + mock_response = '{"batches": [{"batch_id": "batch_id", "created": "2019-01-01T12:00:00.000Z", "enrichment_id": "enrichment_id"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = _service.list_batches( + project_id, + collection_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_batches_all_params_with_retries(self): + # Enable retries and run test_list_batches_all_params. + _service.enable_retries() + self.test_list_batches_all_params() + + # Disable retries and run test_list_batches_all_params. + _service.disable_retries() + self.test_list_batches_all_params() + + @responses.activate + def test_list_batches_value_error(self): + """ + test_list_batches_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches') + mock_response = '{"batches": [{"batch_id": "batch_id", "created": "2019-01-01T12:00:00.000Z", "enrichment_id": "enrichment_id"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_batches(**req_copy) + + def test_list_batches_value_error_with_retries(self): + # Enable retries and run test_list_batches_value_error. + _service.enable_retries() + self.test_list_batches_value_error() + + # Disable retries and run test_list_batches_value_error. + _service.disable_retries() + self.test_list_batches_value_error() + + +class TestPullBatches: + """ + Test Class for pull_batches + """ + + @responses.activate + def test_pull_batches_all_params(self): + """ + pull_batches() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches/testString') + mock_response = '{"file": "file"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + batch_id = 'testString' + + # Invoke method + response = _service.pull_batches( + project_id, + collection_id, + batch_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_pull_batches_all_params_with_retries(self): + # Enable retries and run test_pull_batches_all_params. + _service.enable_retries() + self.test_pull_batches_all_params() + + # Disable retries and run test_pull_batches_all_params. + _service.disable_retries() + self.test_pull_batches_all_params() + + @responses.activate + def test_pull_batches_value_error(self): + """ + test_pull_batches_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches/testString') + mock_response = '{"file": "file"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + batch_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + "batch_id": batch_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.pull_batches(**req_copy) + + def test_pull_batches_value_error_with_retries(self): + # Enable retries and run test_pull_batches_value_error. + _service.enable_retries() + self.test_pull_batches_value_error() + + # Disable retries and run test_pull_batches_value_error. + _service.disable_retries() + self.test_pull_batches_value_error() + + +class TestPushBatches: + """ + Test Class for push_batches + """ + + @responses.activate + def test_push_batches_all_params(self): + """ + push_batches() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches/testString') + mock_response = 'false' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + batch_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + + # Invoke method + response = _service.push_batches( + project_id, + collection_id, + batch_id, + file=file, + filename=filename, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_push_batches_all_params_with_retries(self): + # Enable retries and run test_push_batches_all_params. + _service.enable_retries() + self.test_push_batches_all_params() + + # Disable retries and run test_push_batches_all_params. + _service.disable_retries() + self.test_push_batches_all_params() + + @responses.activate + def test_push_batches_required_params(self): + """ + test_push_batches_required_params() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches/testString') + mock_response = 'false' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + batch_id = 'testString' + + # Invoke method + response = _service.push_batches( + project_id, + collection_id, + batch_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_push_batches_required_params_with_retries(self): + # Enable retries and run test_push_batches_required_params. + _service.enable_retries() + self.test_push_batches_required_params() + + # Disable retries and run test_push_batches_required_params. + _service.disable_retries() + self.test_push_batches_required_params() + + @responses.activate + def test_push_batches_value_error(self): + """ + test_push_batches_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches/testString') + mock_response = 'false' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + batch_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + "batch_id": batch_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.push_batches(**req_copy) + + def test_push_batches_value_error_with_retries(self): + # Enable retries and run test_push_batches_value_error. + _service.enable_retries() + self.test_push_batches_value_error() + + # Disable retries and run test_push_batches_value_error. + _service.disable_retries() + self.test_push_batches_value_error() + + +# endregion +############################################################################## +# End of Service: Batches +############################################################################## + ############################################################################## # Start of Service: DocumentClassifiers ############################################################################## @@ -5653,6 +5973,36 @@ def test_analyzed_result_serialization(self): assert actual_dict == expected_dict +class TestModel_BatchDetails: + """ + Test Class for BatchDetails + """ + + def test_batch_details_serialization(self): + """ + Test serialization/deserialization for BatchDetails + """ + + # Construct a json representation of a BatchDetails model + batch_details_model_json = {} + batch_details_model_json['enrichment_id'] = 'testString' + + # Construct a model instance of BatchDetails by calling from_dict on the json representation + batch_details_model = BatchDetails.from_dict(batch_details_model_json) + assert batch_details_model != False + + # Construct a model instance of BatchDetails by calling from_dict on the json representation + batch_details_model_dict = BatchDetails.from_dict(batch_details_model_json).__dict__ + batch_details_model2 = BatchDetails(**batch_details_model_dict) + + # Verify the model instances are equivalent + assert batch_details_model == batch_details_model2 + + # Convert model instance back to dict and verify no loss of data + batch_details_model_json2 = batch_details_model.to_dict() + assert batch_details_model_json2 == batch_details_model_json + + class TestModel_ClassifierFederatedModel: """ Test Class for ClassifierFederatedModel @@ -7014,6 +7364,41 @@ def test_field_serialization(self): assert field_model_json2 == field_model_json +class TestModel_ListBatchesResponse: + """ + Test Class for ListBatchesResponse + """ + + def test_list_batches_response_serialization(self): + """ + Test serialization/deserialization for ListBatchesResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + batch_details_model = {} # BatchDetails + batch_details_model['enrichment_id'] = 'fd290d8b-53e2-dba1-0000-018a8d150b85' + + # Construct a json representation of a ListBatchesResponse model + list_batches_response_model_json = {} + list_batches_response_model_json['batches'] = [batch_details_model] + + # Construct a model instance of ListBatchesResponse by calling from_dict on the json representation + list_batches_response_model = ListBatchesResponse.from_dict(list_batches_response_model_json) + assert list_batches_response_model != False + + # Construct a model instance of ListBatchesResponse by calling from_dict on the json representation + list_batches_response_model_dict = ListBatchesResponse.from_dict(list_batches_response_model_json).__dict__ + list_batches_response_model2 = ListBatchesResponse(**list_batches_response_model_dict) + + # Verify the model instances are equivalent + assert list_batches_response_model == list_batches_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_batches_response_model_json2 = list_batches_response_model.to_dict() + assert list_batches_response_model_json2 == list_batches_response_model_json + + class TestModel_ListCollectionsResponse: """ Test Class for ListCollectionsResponse @@ -9121,6 +9506,36 @@ def test_webhook_header_serialization(self): assert webhook_header_model_json2 == webhook_header_model_json +class TestModel_PullBatchesResponse: + """ + Test Class for PullBatchesResponse + """ + + def test_pull_batches_response_serialization(self): + """ + Test serialization/deserialization for PullBatchesResponse + """ + + # Construct a json representation of a PullBatchesResponse model + pull_batches_response_model_json = {} + pull_batches_response_model_json['file'] = 'testString' + + # Construct a model instance of PullBatchesResponse by calling from_dict on the json representation + pull_batches_response_model = PullBatchesResponse.from_dict(pull_batches_response_model_json) + assert pull_batches_response_model != False + + # Construct a model instance of PullBatchesResponse by calling from_dict on the json representation + pull_batches_response_model_dict = PullBatchesResponse.from_dict(pull_batches_response_model_json).__dict__ + pull_batches_response_model2 = PullBatchesResponse(**pull_batches_response_model_dict) + + # Verify the model instances are equivalent + assert pull_batches_response_model == pull_batches_response_model2 + + # Convert model instance back to dict and verify no loss of data + pull_batches_response_model_json2 = pull_batches_response_model.to_dict() + assert pull_batches_response_model_json2 == pull_batches_response_model_json + + class TestModel_QueryAggregationQueryCalculationAggregation: """ Test Class for QueryAggregationQueryCalculationAggregation From 22a8b09ae92640635085f3df7bf352d9130bb654 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 22 Nov 2024 12:11:57 -0500 Subject: [PATCH 08/11] chore: update services to version 3.97.0 of sdk generator --- ibm_watson/assistant_v1.py | 431 ++++++++++++------ ibm_watson/discovery_v2.py | 145 ++++-- .../natural_language_understanding_v1.py | 2 +- ibm_watson/speech_to_text_v1.py | 2 +- ibm_watson/text_to_speech_v1.py | 2 +- .../test_natural_language_understanding_v1.py | 19 +- test/unit/test_assistant_v1.py | 23 +- test/unit/test_discovery_v2.py | 15 +- .../test_natural_language_understanding_v1.py | 11 +- test/unit/test_speech_to_text_v1.py | 11 +- test/unit/test_text_to_speech_v1.py | 11 +- 11 files changed, 416 insertions(+), 256 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index b98b688b..7528355d 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -4820,6 +4820,8 @@ class Context: :param dict system: (optional) For internal use only. :param MessageContextMetadata metadata: (optional) Metadata related to the message. + + This type supports additional properties of type object. Any context variable. """ # The set of defined properties for the class @@ -4831,7 +4833,7 @@ def __init__( conversation_id: Optional[str] = None, system: Optional[dict] = None, metadata: Optional['MessageContextMetadata'] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a Context object. @@ -4843,13 +4845,22 @@ def __init__( :param dict system: (optional) For internal use only. :param MessageContextMetadata metadata: (optional) Metadata related to the message. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any context variable. """ self.conversation_id = conversation_id self.system = system self.metadata = metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in Context._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'Context': @@ -4861,8 +4872,13 @@ def from_dict(cls, _dict: Dict) -> 'Context': args['system'] = system if (metadata := _dict.get('metadata')) is not None: args['metadata'] = MessageContextMetadata.from_dict(metadata) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -4883,10 +4899,10 @@ def to_dict(self) -> Dict: _dict['metadata'] = self.metadata else: _dict['metadata'] = self.metadata.to_dict() - for _key in [ - k for k in vars(self).keys() if k not in Context._properties + for k in [ + _k for _k in vars(self).keys() if _k not in Context._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -4894,25 +4910,31 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of Context""" + """Return the additional properties from this instance of Context in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in Context._properties + for k in [ + _k for _k in vars(self).keys() if _k not in Context._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of Context""" - for _key in [ - k for k in vars(self).keys() if k not in Context._properties + """Set a dictionary of additional properties in this instance of Context""" + for k in [ + _k for _k in vars(self).keys() if _k not in Context._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in Context._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in Context._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this Context object.""" @@ -6050,6 +6072,8 @@ class DialogNodeContext: :param dict integrations: (optional) Context data intended for specific integrations. + + This type supports additional properties of type object. Any context variable. """ # The set of defined properties for the class @@ -6059,18 +6083,27 @@ def __init__( self, *, integrations: Optional[dict] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a DialogNodeContext object. :param dict integrations: (optional) Context data intended for specific integrations. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any context variable. """ self.integrations = integrations - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in DialogNodeContext._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'DialogNodeContext': @@ -6078,8 +6111,13 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeContext': args = {} if (integrations := _dict.get('integrations')) is not None: args['integrations'] = integrations - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -6092,11 +6130,11 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeContext._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeContext._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -6104,27 +6142,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of DialogNodeContext""" + """Return the additional properties from this instance of DialogNodeContext in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeContext._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeContext._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of DialogNodeContext""" - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeContext._properties + """Set a dictionary of additional properties in this instance of DialogNodeContext""" + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeContext._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in DialogNodeContext._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in DialogNodeContext._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this DialogNodeContext object.""" @@ -6317,6 +6361,9 @@ class DialogNodeOutput: [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-responses-json). :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. + + This type supports additional properties of type object. Any additional data included + in the dialog node output. """ # The set of defined properties for the class @@ -6328,7 +6375,7 @@ def __init__( generic: Optional[List['DialogNodeOutputGeneric']] = None, integrations: Optional[dict] = None, modifiers: Optional['DialogNodeOutputModifiers'] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a DialogNodeOutput object. @@ -6340,13 +6387,23 @@ def __init__( [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-responses-json). :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any additional data included in the + dialog node output. """ self.generic = generic self.integrations = integrations self.modifiers = modifiers - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in DialogNodeOutput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': @@ -6360,8 +6417,13 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': args['integrations'] = integrations if (modifiers := _dict.get('modifiers')) is not None: args['modifiers'] = DialogNodeOutputModifiers.from_dict(modifiers) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -6387,11 +6449,11 @@ def to_dict(self) -> Dict: _dict['modifiers'] = self.modifiers else: _dict['modifiers'] = self.modifiers.to_dict() - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeOutput._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeOutput._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -6399,27 +6461,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of DialogNodeOutput""" + """Return the additional properties from this instance of DialogNodeOutput in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeOutput._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeOutput._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of DialogNodeOutput""" - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeOutput._properties + """Set a dictionary of additional properties in this instance of DialogNodeOutput""" + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeOutput._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in DialogNodeOutput._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in DialogNodeOutput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this DialogNodeOutput object.""" @@ -8635,6 +8703,9 @@ class MessageInput: autocorrection is disabled. :param str original_text: (optional) The original user input text. This property is returned only if autocorrection is enabled and the user input was corrected. + + This type supports additional properties of type object. Any additional data included + with the message input. """ # The set of defined properties for the class @@ -8651,7 +8722,7 @@ def __init__( spelling_auto_correct: Optional[bool] = None, suggested_text: Optional[str] = None, original_text: Optional[str] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a MessageInput object. @@ -8669,15 +8740,25 @@ def __init__( the original text is returned in the **original_text** property of the message response. This property overrides the value of the **spelling_auto_correct** property in the workspace settings. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any additional data included with the + message input. """ self.text = text self.spelling_suggestions = spelling_suggestions self.spelling_auto_correct = spelling_auto_correct self.suggested_text = suggested_text self.original_text = original_text - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in MessageInput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'MessageInput': @@ -8695,8 +8776,13 @@ def from_dict(cls, _dict: Dict) -> 'MessageInput': args['suggested_text'] = suggested_text if (original_text := _dict.get('original_text')) is not None: args['original_text'] = original_text - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -8721,11 +8807,11 @@ def to_dict(self) -> Dict: if hasattr(self, 'original_text') and getattr( self, 'original_text') is not None: _dict['original_text'] = getattr(self, 'original_text') - for _key in [ - k for k in vars(self).keys() - if k not in MessageInput._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageInput._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -8733,27 +8819,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of MessageInput""" + """Return the additional properties from this instance of MessageInput in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in MessageInput._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageInput._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of MessageInput""" - for _key in [ - k for k in vars(self).keys() - if k not in MessageInput._properties + """Set a dictionary of additional properties in this instance of MessageInput""" + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageInput._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in MessageInput._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in MessageInput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this MessageInput object.""" @@ -9162,6 +9254,9 @@ class OutputData: :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. + + This type supports additional properties of type object. Any additional data included + with the output. """ # The set of defined properties for the class @@ -9176,7 +9271,7 @@ def __init__( nodes_visited_details: Optional[ List['DialogNodeVisitedDetails']] = None, generic: Optional[List['RuntimeResponseGeneric']] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a OutputData object. @@ -9194,14 +9289,24 @@ def __init__( :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. + :param object **kwargs: (optional) Any additional data included with the + output. """ self.nodes_visited = nodes_visited self.nodes_visited_details = nodes_visited_details self.log_messages = log_messages self.generic = generic - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in OutputData._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'OutputData': @@ -9227,8 +9332,13 @@ def from_dict(cls, _dict: Dict) -> 'OutputData': args['generic'] = [ RuntimeResponseGeneric.from_dict(v) for v in generic ] - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -9266,10 +9376,11 @@ def to_dict(self) -> Dict: else: generic_list.append(v.to_dict()) _dict['generic'] = generic_list - for _key in [ - k for k in vars(self).keys() if k not in OutputData._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in OutputData._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -9277,25 +9388,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of OutputData""" + """Return the additional properties from this instance of OutputData in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in OutputData._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in OutputData._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of OutputData""" - for _key in [ - k for k in vars(self).keys() if k not in OutputData._properties + """Set a dictionary of additional properties in this instance of OutputData""" + for k in [ + _k for _k in vars(self).keys() + if _k not in OutputData._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in OutputData._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in OutputData._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this OutputData object.""" @@ -11446,6 +11565,8 @@ class WorkspaceSystemSettings: related to detection of irrelevant input. :param WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings related to the version of the training algorithms currently used by the skill. + + This type supports additional properties of type object. For internal use only. """ # The set of defined properties for the class @@ -11468,7 +11589,7 @@ def __init__( 'WorkspaceSystemSettingsSystemEntities'] = None, off_topic: Optional['WorkspaceSystemSettingsOffTopic'] = None, nlp: Optional['WorkspaceSystemSettingsNlp'] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a WorkspaceSystemSettings object. @@ -11494,7 +11615,7 @@ def __init__( :param WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings related to the version of the training algorithms currently used by the skill. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) For internal use only. """ self.tooling = tooling self.disambiguation = disambiguation @@ -11504,8 +11625,17 @@ def __init__( self.system_entities = system_entities self.off_topic = off_topic self.nlp = nlp - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in WorkspaceSystemSettings._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': @@ -11534,8 +11664,13 @@ def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': off_topic) if (nlp := _dict.get('nlp')) is not None: args['nlp'] = WorkspaceSystemSettingsNlp.from_dict(nlp) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -11582,11 +11717,11 @@ def to_dict(self) -> Dict: _dict['nlp'] = self.nlp else: _dict['nlp'] = self.nlp.to_dict() - for _key in [ - k for k in vars(self).keys() - if k not in WorkspaceSystemSettings._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in WorkspaceSystemSettings._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -11594,27 +11729,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of WorkspaceSystemSettings""" + """Return the additional properties from this instance of WorkspaceSystemSettings in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in WorkspaceSystemSettings._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in WorkspaceSystemSettings._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of WorkspaceSystemSettings""" - for _key in [ - k for k in vars(self).keys() - if k not in WorkspaceSystemSettings._properties + """Set a dictionary of additional properties in this instance of WorkspaceSystemSettings""" + for k in [ + _k for _k in vars(self).keys() + if _k not in WorkspaceSystemSettings._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in WorkspaceSystemSettings._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in WorkspaceSystemSettings._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this WorkspaceSystemSettings object.""" diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index e5c0fbe7..f9a99490 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ IBM Watson® Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive better @@ -4112,6 +4112,9 @@ class AnalyzedResult: Result of the document analysis. :param dict metadata: (optional) Metadata that was specified with the request. + + This type supports additional properties of type object. The remaining key-value + pairs. """ # The set of defined properties for the class @@ -4121,18 +4124,27 @@ def __init__( self, *, metadata: Optional[dict] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a AnalyzedResult object. :param dict metadata: (optional) Metadata that was specified with the request. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) The remaining key-value pairs. """ self.metadata = metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in AnalyzedResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': @@ -4140,8 +4152,13 @@ def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': args = {} if (metadata := _dict.get('metadata')) is not None: args['metadata'] = metadata - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -4154,11 +4171,11 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in AnalyzedResult._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -4166,27 +4183,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of AnalyzedResult""" + """Return the additional properties from this instance of AnalyzedResult in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in AnalyzedResult._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of AnalyzedResult""" - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties + """Set a dictionary of additional properties in this instance of AnalyzedResult""" + for k in [ + _k for _k in vars(self).keys() + if _k not in AnalyzedResult._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in AnalyzedResult._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in AnalyzedResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this AnalyzedResult object.""" @@ -10266,6 +10289,9 @@ class QueryResult: :param List[QueryResultPassage] document_passages: (optional) Passages from the document that best matches the query. Returned if **passages.per_document** is `true`. + + This type supports additional properties of type object. The remaining key-value + pairs. """ # The set of defined properties for the class @@ -10279,7 +10305,7 @@ def __init__( *, metadata: Optional[dict] = None, document_passages: Optional[List['QueryResultPassage']] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a QueryResult object. @@ -10290,14 +10316,23 @@ def __init__( :param List[QueryResultPassage] document_passages: (optional) Passages from the document that best matches the query. Returned if **passages.per_document** is `true`. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) The remaining key-value pairs. """ self.document_id = document_id self.metadata = metadata self.result_metadata = result_metadata self.document_passages = document_passages - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in QueryResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'QueryResult': @@ -10322,8 +10357,13 @@ def from_dict(cls, _dict: Dict) -> 'QueryResult': args['document_passages'] = [ QueryResultPassage.from_dict(v) for v in document_passages ] - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -10353,10 +10393,11 @@ def to_dict(self) -> Dict: else: document_passages_list.append(v.to_dict()) _dict['document_passages'] = document_passages_list - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in QueryResult._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -10364,25 +10405,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of QueryResult""" + """Return the additional properties from this instance of QueryResult in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in QueryResult._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of QueryResult""" - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties + """Set a dictionary of additional properties in this instance of QueryResult""" + for k in [ + _k for _k in vars(self).keys() + if _k not in QueryResult._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in QueryResult._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in QueryResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this QueryResult object.""" diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index d56cb364..c3561e27 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index b0831533..459564a8 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's speech-recognition capabilities to produce transcripts of spoken audio. The service can diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 23fe1b48..145fdcae 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, diff --git a/test/integration/test_natural_language_understanding_v1.py b/test/integration/test_natural_language_understanding_v1.py index faedb759..1255b506 100644 --- a/test/integration/test_natural_language_understanding_v1.py +++ b/test/integration/test_natural_language_understanding_v1.py @@ -6,17 +6,22 @@ import json import time from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -@pytest.mark.skipif(os.getenv('NATURAL_LANGUAGE_UNDERSTANDING_APIKEY') is None, - reason='requires NATURAL_LANGUAGE_UNDERSTANDING_APIKEY') class TestNaturalLanguageUnderstandingV1(TestCase): def setUp(self): - self.natural_language_understanding = ibm_watson.NaturalLanguageUnderstandingV1(version='2018-03-16') - self.natural_language_understanding.set_default_headers({ - 'X-Watson-Learning-Opt-Out': '1', - 'X-Watson-Test': '1' - }) + + with open('./auth.json') as f: + data = json.load(f) + nlu_auth = data.get("nlu") + + self.authenticator = IAMAuthenticator(nlu_auth.get("apikey")) + self.natural_language_understanding = ibm_watson.NaturalLanguageUnderstandingV1(version='2018-03-16', authenticator=self.authenticator) + self.natural_language_understanding.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) def test_analyze(self): response = self.natural_language_understanding.analyze( diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 5b307c5e..82781955 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -47,20 +47,13 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') @@ -8539,7 +8532,7 @@ def test_context_serialization(self): expected_dict = {'foo': 'testString'} context_model.set_properties(expected_dict) actual_dict = context_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_Counterexample: @@ -8995,7 +8988,7 @@ def test_dialog_node_context_serialization(self): expected_dict = {'foo': 'testString'} dialog_node_context_model.set_properties(expected_dict) actual_dict = dialog_node_context_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_DialogNodeNextStep: @@ -9088,7 +9081,7 @@ def test_dialog_node_output_serialization(self): expected_dict = {'foo': 'testString'} dialog_node_output_model.set_properties(expected_dict) actual_dict = dialog_node_output_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_DialogNodeOutputConnectToAgentTransferInfo: @@ -10476,7 +10469,7 @@ def test_message_input_serialization(self): expected_dict = {'foo': 'testString'} message_input_model.set_properties(expected_dict) actual_dict = message_input_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_MessageRequest: @@ -10819,7 +10812,7 @@ def test_output_data_serialization(self): expected_dict = {'foo': 'testString'} output_data_model.set_properties(expected_dict) actual_dict = output_data_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_Pagination: @@ -11823,7 +11816,7 @@ def test_workspace_system_settings_serialization(self): expected_dict = {'foo': 'testString'} workspace_system_settings_model.set_properties(expected_dict) actual_dict = workspace_system_settings_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_WorkspaceSystemSettingsDisambiguation: diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 0e172b94..10401163 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -49,20 +49,13 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') @@ -5970,7 +5963,7 @@ def test_analyzed_result_serialization(self): expected_dict = {'foo': 'testString'} analyzed_result_model.set_properties(expected_dict) actual_dict = analyzed_result_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_BatchDetails: @@ -8365,7 +8358,7 @@ def test_query_result_serialization(self): expected_dict = {'foo': 'testString'} query_result_model.set_properties(expected_dict) actual_dict = query_result_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_QueryResultMetadata: diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 86e529fc..40ca030a 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -49,20 +49,13 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 781732cc..658ae899 100644 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -45,20 +45,13 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 26341c54..e151e450 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -45,20 +45,13 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') From d58fb104de9d8e018ae9df4ed1bc95ce6b78beb9 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 22 Nov 2024 12:24:15 -0500 Subject: [PATCH 09/11] feat(WxA): add new functions and update required params BREAKING CHANGE: `environmentId` now required for `message` and `messageStateless` functions Add support for message streaming and new APIs New functions: createProviders, listProviders, updateProviders, createReleaseExport, downloadReleaseExport, createReleaseImport, getReleaseImportStatus , messageStream, messageStreamStateless --- ibm_watson/assistant_v2.py | 13147 +++++++++++++++++++++---------- test/unit/test_assistant_v2.py | 9822 ++++++++++++++++------- 2 files changed, 15709 insertions(+), 7260 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 764f567f..31ff57d2 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ The IBM® watsonx™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -29,7 +29,7 @@ from datetime import datetime from enum import Enum -from typing import Dict, List, Optional +from typing import BinaryIO, Dict, List, Optional import json import sys @@ -78,6 +78,214 @@ def __init__( self.version = version self.configure_service(service_name) + ######################### + # Conversational skill providers + ######################### + + def create_provider( + self, + provider_id: str, + specification: 'ProviderSpecification', + private: 'ProviderPrivate', + **kwargs, + ) -> DetailedResponse: + """ + Create a conversational skill provider. + + Create a new conversational skill provider. + + :param str provider_id: The unique identifier of the provider. + :param ProviderSpecification specification: The specification of the + provider. + :param ProviderPrivate private: Private information of the provider. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ProviderResponse` object + """ + + if provider_id is None: + raise ValueError('provider_id must be provided') + if specification is None: + raise ValueError('specification must be provided') + if private is None: + raise ValueError('private must be provided') + specification = convert_model(specification) + private = convert_model(private) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_provider', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'provider_id': provider_id, + 'specification': specification, + 'private': private, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/providers' + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def list_providers( + self, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + List conversational skill providers. + + List the conversational skill providers associated with a Watson Assistant service + instance. + + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned conversational + skill providers will be sorted. To reverse the sort order, prefix the value + with a minus sign (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ProviderCollection` object + """ + + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_providers', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/providers' + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def update_provider( + self, + provider_id: str, + specification: 'ProviderSpecification', + private: 'ProviderPrivate', + **kwargs, + ) -> DetailedResponse: + """ + Update a conversational skill provider. + + Update a new conversational skill provider. + + :param str provider_id: Unique identifier of the conversational skill + provider. + :param ProviderSpecification specification: The specification of the + provider. + :param ProviderPrivate private: Private information of the provider. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ProviderResponse` object + """ + + if not provider_id: + raise ValueError('provider_id must be provided') + if specification is None: + raise ValueError('specification must be provided') + if private is None: + raise ValueError('private must be provided') + specification = convert_model(specification) + private = convert_model(private) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_provider', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'specification': specification, + 'private': private, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['provider_id'] + path_param_values = self.encode_path_vars(provider_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/providers/{provider_id}'.format(**path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + ######################### # Assistants ######################### @@ -426,6 +634,7 @@ def delete_session( def message( self, assistant_id: str, + environment_id: str, session_id: str, *, input: Optional['MessageInput'] = None, @@ -452,6 +661,10 @@ def message( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. :param str session_id: Unique identifier of the session. :param MessageInput input: (optional) An input object that includes the input text. @@ -478,6 +691,8 @@ def message( if not assistant_id: raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') if not session_id: raise ValueError('session_id must be provided') if input is not None: @@ -510,8 +725,9 @@ def message( del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id', 'session_id'] - path_param_values = self.encode_path_vars(assistant_id, session_id) + path_param_keys = ['assistant_id', 'environment_id', 'session_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id, + session_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/sessions/{session_id}/message'.format( **path_param_dict) @@ -529,6 +745,7 @@ def message( def message_stateless( self, assistant_id: str, + environment_id: str, *, input: Optional['StatelessMessageInput'] = None, context: Optional['StatelessMessageContext'] = None, @@ -553,6 +770,10 @@ def message_stateless( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. :param StatelessMessageInput input: (optional) An input object that includes the input text. :param StatelessMessageContext context: (optional) Context data for the @@ -579,6 +800,8 @@ def message_stateless( if not assistant_id: raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') if input is not None: input = convert_model(input) if context is not None: @@ -609,8 +832,8 @@ def message_stateless( del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id'] - path_param_values = self.encode_path_vars(assistant_id) + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/message'.format(**path_param_dict) request = self.prepare_request( @@ -625,44 +848,82 @@ def message_stateless( return response ######################### - # Bulk classify + # Message Stream ######################### - def bulk_classify( + def message_stream( self, - skill_id: str, - input: List['BulkClassifyUtterance'], + assistant_id: str, + environment_id: str, + session_id: str, + *, + input: Optional['MessageInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, **kwargs, ) -> DetailedResponse: """ - Identify intents and entities in multiple user utterances. + Send user input to assistant (stateful). - Send multiple user inputs to a dialog skill in a single request and receive - information about the intents and entities recognized in each input. This method - is useful for testing and comparing the performance of different skills or skill - versions. - This method is available only with Enterprise with Data Isolation plans. + Send user input to an assistant and receive a streamed response, with conversation + state (including context data) stored by watsonx Assistant for the duration of the + session. - :param str skill_id: Unique identifier of the skill. To find the skill ID - in the watsonx Assistant user interface, open the skill settings and click - **API Details**. - :param List[BulkClassifyUtterance] input: An array of input utterances to - classify. + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param str session_id: Unique identifier of the session. + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object + :rtype: DetailedResponse with `BinaryIO` result """ - if not skill_id: - raise ValueError('skill_id must be provided') - if input is None: - raise ValueError('input must be provided') - input = [convert_model(x) for x in input] + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + if not session_id: + raise ValueError('session_id must be provided') + if input is not None: + input = convert_model(input) + if context is not None: + context = convert_model(context) headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='bulk_classify', + operation_id='message_stream', ) headers.update(sdk_headers) @@ -672,6 +933,8 @@ def bulk_classify( data = { 'input': input, + 'context': context, + 'user_id': user_id, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -680,12 +943,13 @@ def bulk_classify( if 'headers' in kwargs: headers.update(kwargs.get('headers')) del kwargs['headers'] - headers['Accept'] = 'application/json' + headers['Accept'] = 'text/event-stream' - path_param_keys = ['skill_id'] - path_param_values = self.encode_path_vars(skill_id) + path_param_keys = ['assistant_id', 'environment_id', 'session_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id, + session_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/skills/{skill_id}/workspace/bulk_classify'.format( + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/sessions/{session_id}/message_stream'.format( **path_param_dict) request = self.prepare_request( method='POST', @@ -698,15 +962,194 @@ def bulk_classify( response = self.send(request, **kwargs) return response - ######################### - # Logs - ######################### - - def list_logs( + def message_stream_stateless( self, assistant_id: str, + environment_id: str, *, - sort: Optional[str] = None, + input: Optional['MessageInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Send user input to assistant (stateless). + + Send user input to an assistant and receive a response, with conversation state + (including context data) managed by your application. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `BinaryIO` result + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + if input is not None: + input = convert_model(input) + if context is not None: + context = convert_model(context) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message_stream_stateless', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'input': input, + 'context': context, + 'user_id': user_id, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'text/event-stream' + + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/message_stream'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Bulk classify + ######################### + + def bulk_classify( + self, + skill_id: str, + input: List['BulkClassifyUtterance'], + **kwargs, + ) -> DetailedResponse: + """ + Identify intents and entities in multiple user utterances. + + Send multiple user inputs to a dialog skill in a single request and receive + information about the intents and entities recognized in each input. This method + is useful for testing and comparing the performance of different skills or skill + versions. + This method is available only with Enterprise with Data Isolation plans. + + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the watsonx Assistant user interface, open the skill settings and click + **API Details**. + :param List[BulkClassifyUtterance] input: An array of input utterances to + classify. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object + """ + + if not skill_id: + raise ValueError('skill_id must be provided') + if input is None: + raise ValueError('input must be provided') + input = [convert_model(x) for x in input] + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='bulk_classify', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'input': input, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['skill_id'] + path_param_values = self.encode_path_vars(skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/skills/{skill_id}/workspace/bulk_classify'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Logs + ######################### + + def list_logs( + self, + assistant_id: str, + *, + sort: Optional[str] = None, filter: Optional[str] = None, page_limit: Optional[int] = None, cursor: Optional[str] = None, @@ -1020,7 +1463,7 @@ def update_environment( *, name: Optional[str] = None, description: Optional[str] = None, - orchestration: Optional['BaseEnvironmentOrchestration'] = None, + orchestration: Optional['UpdateEnvironmentOrchestration'] = None, session_timeout: Optional[int] = None, skill_references: Optional[List['EnvironmentSkill']] = None, **kwargs, @@ -1050,7 +1493,7 @@ def update_environment( API does not support creating environments. :param str name: (optional) The name of the environment. :param str description: (optional) The description of the environment. - :param BaseEnvironmentOrchestration orchestration: (optional) The search + :param UpdateEnvironmentOrchestration orchestration: (optional) The search skill orchestration settings for the environment. :param int session_timeout: (optional) The session inactivity timeout setting for the environment (in seconds). @@ -1500,20 +1943,25 @@ def deploy_release( response = self.send(request, **kwargs) return response - ######################### - # Skills - ######################### - - def get_skill( + def create_release_export( self, assistant_id: str, - skill_id: str, + release: str, + *, + include_audit: Optional[bool] = None, **kwargs, ) -> DetailedResponse: """ - Get skill. + Create release export. - Get information about a skill. + Initiate an asynchronous process which will create a downloadable Zip file + artifact (/package) for an assistant release. This artifact will contain Action + and/or Dialog skills that are part of the release. The Dialog skill will only be + included in the event that coexistence is enabled on the assistant. The expected + workflow with the use of Release Export endpoint is to first initiate the creation + of the artifact with the POST endpoint and then poll the GET endpoint to retrieve + the artifact. Once the artifact has been created, it will last for the duration + (/scope) of the release. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1527,28 +1975,29 @@ def get_skill( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. - :param str skill_id: Unique identifier of the skill. To find the skill ID - in the watsonx Assistant user interface, open the skill settings and click - **API Details**. + :param str release: Unique identifier of the release. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Skill` object + :rtype: DetailedResponse with `dict` result representing a `CreateReleaseExportWithStatusErrors` object """ if not assistant_id: raise ValueError('assistant_id must be provided') - if not skill_id: - raise ValueError('skill_id must be provided') + if not release: + raise ValueError('release must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_skill', + operation_id='create_release_export', ) headers.update(sdk_headers) params = { 'version': self.version, + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -1556,13 +2005,13 @@ def get_skill( del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id', 'skill_id'] - path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + url = '/v2/assistants/{assistant_id}/releases/{release}/export'.format( **path_param_dict) request = self.prepare_request( - method='GET', + method='POST', url=url, headers=headers, params=params, @@ -1571,25 +2020,33 @@ def get_skill( response = self.send(request, **kwargs) return response - def update_skill( + def download_release_export( self, assistant_id: str, - skill_id: str, + release: str, *, - name: Optional[str] = None, - description: Optional[str] = None, - workspace: Optional[dict] = None, - dialog_settings: Optional[dict] = None, - search_settings: Optional['SearchSettings'] = None, + accept: Optional[str] = None, + include_audit: Optional[bool] = None, **kwargs, ) -> DetailedResponse: """ - Update skill. - - Update a skill with new or modified data. - **Note:** The update is performed asynchronously; you can see the status of the - update by calling the **Get skill** method and checking the value of the - **status** property. + Get release export. + + A dual function endpoint to either retrieve the Zip file artifact that is + associated with an assistant release or, retrieve the status of the artifact's + creation. It is assumed that the artifact creation was already initiated prior to + calling this endpoint. In the event that the artifact is not yet created and ready + for download, this endpoint can be used to poll the system until the creation is + completed or has failed. On the other hand, if the artifact is created, this + endpoint will return the Zip file artifact as an octet stream. Once the artifact + has been created, it will last for the duration (/scope) of the release.

When you will have downloaded the Zip file artifact, you have one of three ways + to import it into an assistant's draft environment. These are as follows.
  1. Import the zip package in Tooling via "Assistant Settings" -> + "Download/Upload files" -> "Upload" -> "Assistant only".
  2. Import the + zip package via "Create release import" endpoint using the APIs.
  3. Extract + the contents of the Zip file artifact and individually import the skill JSONs via + skill update endpoints.
. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1603,98 +2060,82 @@ def update_skill( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. - :param str skill_id: Unique identifier of the skill. To find the skill ID - in the watsonx Assistant user interface, open the skill settings and click - **API Details**. - :param str name: (optional) The name of the skill. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This - string cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param dict dialog_settings: (optional) For internal use only. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, - and are not included in **Export skills** responses. + :param str release: Unique identifier of the release. + :param str accept: (optional) The type of the response: application/json or + application/octet-stream. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Skill` object + :rtype: DetailedResponse with `dict` result representing a `CreateReleaseExportWithStatusErrors` object """ if not assistant_id: raise ValueError('assistant_id must be provided') - if not skill_id: - raise ValueError('skill_id must be provided') - if search_settings is not None: - search_settings = convert_model(search_settings) - headers = {} + if not release: + raise ValueError('release must be provided') + headers = { + 'Accept': accept, + } sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_skill', + operation_id='download_release_export', ) headers.update(sdk_headers) params = { 'version': self.version, + 'include_audit': include_audit, } - data = { - 'name': name, - 'description': description, - 'workspace': workspace, - 'dialog_settings': dialog_settings, - 'search_settings': search_settings, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - if 'headers' in kwargs: headers.update(kwargs.get('headers')) del kwargs['headers'] - headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id', 'skill_id'] - path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + url = '/v2/assistants/{assistant_id}/releases/{release}/export'.format( **path_param_dict) request = self.prepare_request( - method='POST', + method='GET', url=url, headers=headers, params=params, - data=data, ) response = self.send(request, **kwargs) return response - def export_skills( + def create_release_import( self, assistant_id: str, + body: BinaryIO, *, include_audit: Optional[bool] = None, **kwargs, ) -> DetailedResponse: """ - Export skills. - - Asynchronously export the action skill and dialog skill (if enabled) for the - assistant. Use this method to save all skill data so that you can import it to a - different assistant using the **Import skills** method. - A successful call to this method only initiates an asynchronous export. The - exported JSON data is not available until processing completes. - After the initial request is submitted, you can poll the status of the operation - by calling the same request again and checking the value of the **status** - property. If an error occurs (indicated by a **status** value of `Failed`), the - `status_description` property provides more information about the error, and the - `status_errors` property contains an array of error messages that caused the - failure. - When processing has completed, the request returns the exported JSON data. - Remember that the usual rate limits apply. + Create release import. + + Import a previously exported assistant release Zip file artifact (/package) into + an assistant. This endpoint creates (/initiates) an asynchronous task (/job) in + the background which will import the artifact contents into the draft environment + of the assistant on which this endpoint is called. Specifically, the asynchronous + operation will override the action and/or dialog skills in the assistant. It will + be worth noting that when the artifact that is provided to this endpoint is from + an assistant release which has coexistence enabled (i.e., it has both action and + dialog skills), the import process will automatically enable coexistence, if not + already enabled, on the assistant into which said artifact is being uploaded to. + On the other hand, if the artifact package being imported only has action skill in + it, the import asynchronous process will only override the draft environment's + action skill, regardless of whether coexistence is enabled on the assistant into + which the package is being imported. Lastly, the system will only run one + asynchronous import at a time on an assistant. As such, consecutive imports will + override previous import's updates to the skills in the draft environment. Once + created, you may poll the completion of the import via the "Get release import + Status" endpoint. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1708,20 +2149,24 @@ def export_skills( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. + :param BinaryIO body: Request body is an Octet-stream of the artifact Zip + file that is being imported. :param bool include_audit: (optional) Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SkillsExport` object + :rtype: DetailedResponse with `dict` result representing a `CreateAssistantReleaseImportResponse` object """ if not assistant_id: raise ValueError('assistant_id must be provided') + if body is None: + raise ValueError('body must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='export_skills', + operation_id='create_release_import', ) headers.update(sdk_headers) @@ -1730,6 +2175,9 @@ def export_skills( 'include_audit': include_audit, } + data = body + headers['content-type'] = 'application/octet-stream' + if 'headers' in kwargs: headers.update(kwargs.get('headers')) del kwargs['headers'] @@ -1738,39 +2186,30 @@ def export_skills( path_param_keys = ['assistant_id'] path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/skills_export'.format( - **path_param_dict) + url = '/v2/assistants/{assistant_id}/import'.format(**path_param_dict) request = self.prepare_request( - method='GET', + method='POST', url=url, headers=headers, params=params, + data=data, ) response = self.send(request, **kwargs) return response - def import_skills( + def get_release_import_status( self, assistant_id: str, - assistant_skills: List['SkillImport'], - assistant_state: 'AssistantState', *, include_audit: Optional[bool] = None, **kwargs, ) -> DetailedResponse: """ - Import skills. + Get release import Status. - Asynchronously import skills into an existing assistant from a previously exported - file. - The request body for this method should contain the response data that was - received from a previous call to the **Export skills** method, without - modification. - A successful call to this method initiates an asynchronous import. The updated - skills belonging to the assistant are not available until processing completes. To - check the status of the asynchronous import operation, use the **Get status of - skills import** method. + Monitor the status of an assistant release import. You may poll this endpoint + until the status of the import has either succeeded or failed. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1784,31 +2223,20 @@ def import_skills( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. - :param List[SkillImport] assistant_skills: An array of objects describing - the skills for the assistant. Included in responses only if - **status**=`Available`. - :param AssistantState assistant_state: Status information about the skills - for the assistant. Included in responses only if **status**=`Available`. :param bool include_audit: (optional) Whether to include the audit properties (`created` and `updated` timestamps) in the response. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object + :rtype: DetailedResponse with `dict` result representing a `MonitorAssistantReleaseImportArtifactResponse` object """ if not assistant_id: raise ValueError('assistant_id must be provided') - if assistant_skills is None: - raise ValueError('assistant_skills must be provided') - if assistant_state is None: - raise ValueError('assistant_state must be provided') - assistant_skills = [convert_model(x) for x in assistant_skills] - assistant_state = convert_model(assistant_state) headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='import_skills', + operation_id='get_release_import_status', ) headers.update(sdk_headers) @@ -1817,14 +2245,6 @@ def import_skills( 'include_audit': include_audit, } - data = { - 'assistant_skills': assistant_skills, - 'assistant_state': assistant_state, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - if 'headers' in kwargs: headers.update(kwargs.get('headers')) del kwargs['headers'] @@ -1833,29 +2253,31 @@ def import_skills( path_param_keys = ['assistant_id'] path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/skills_import'.format( - **path_param_dict) + url = '/v2/assistants/{assistant_id}/import'.format(**path_param_dict) request = self.prepare_request( - method='POST', + method='GET', url=url, headers=headers, params=params, - data=data, ) response = self.send(request, **kwargs) return response - def import_skills_status( + ######################### + # Skills + ######################### + + def get_skill( self, assistant_id: str, + skill_id: str, **kwargs, ) -> DetailedResponse: """ - Get status of skills import. + Get skill. - Retrieve the status of an asynchronous import operation previously initiated by - using the **Import skills** method. + Get information about a skill. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1869,18 +2291,23 @@ def import_skills_status( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the watsonx Assistant user interface, open the skill settings and click + **API Details**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object + :rtype: DetailedResponse with `dict` result representing a `Skill` object """ if not assistant_id: raise ValueError('assistant_id must be provided') + if not skill_id: + raise ValueError('skill_id must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='import_skills_status', + operation_id='get_skill', ) headers.update(sdk_headers) @@ -1893,10 +2320,10 @@ def import_skills_status( del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id'] - path_param_values = self.encode_path_vars(assistant_id) + path_param_keys = ['assistant_id', 'skill_id'] + path_param_values = self.encode_path_vars(assistant_id, skill_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/skills_import/status'.format( + url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( **path_param_dict) request = self.prepare_request( method='GET', @@ -1908,308 +2335,460 @@ def import_skills_status( response = self.send(request, **kwargs) return response - -class ListAssistantsEnums: - """ - Enums for list_assistants parameters. - """ - - class Sort(str, Enum): - """ - The attribute by which returned assistants will be sorted. To reverse the sort - order, prefix the value with a minus sign (`-`). - """ - - NAME = 'name' - UPDATED = 'updated' - - -class ListEnvironmentsEnums: - """ - Enums for list_environments parameters. - """ - - class Sort(str, Enum): - """ - The attribute by which returned environments will be sorted. To reverse the sort - order, prefix the value with a minus sign (`-`). + def update_skill( + self, + assistant_id: str, + skill_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + dialog_settings: Optional[dict] = None, + search_settings: Optional['SearchSettings'] = None, + **kwargs, + ) -> DetailedResponse: """ + Update skill. - NAME = 'name' - UPDATED = 'updated' - - -class ListReleasesEnums: - """ - Enums for list_releases parameters. - """ + Update a skill with new or modified data. + **Note:** The update is performed asynchronously; you can see the status of the + update by calling the **Get skill** method and checking the value of the + **status** property. - class Sort(str, Enum): - """ - The attribute by which returned workspaces will be sorted. To reverse the sort - order, prefix the value with a minus sign (`-`). + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the watsonx Assistant user interface, open the skill settings and click + **API Details**. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Skill` object """ - NAME = 'name' - UPDATED = 'updated' + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not skill_id: + raise ValueError('skill_id must be provided') + if search_settings is not None: + search_settings = convert_model(search_settings) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_skill', + ) + headers.update(sdk_headers) + params = { + 'version': self.version, + } -############################################################################## -# Models -############################################################################## + data = { + 'name': name, + 'description': description, + 'workspace': workspace, + 'dialog_settings': dialog_settings, + 'search_settings': search_settings, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -class AgentAvailabilityMessage: - """ - AgentAvailabilityMessage. + path_param_keys = ['assistant_id', 'skill_id'] + path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) - :param str message: (optional) The text of the message. - """ + response = self.send(request, **kwargs) + return response - def __init__( + def export_skills( self, + assistant_id: str, *, - message: Optional[str] = None, - ) -> None: + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ - Initialize a AgentAvailabilityMessage object. + Export skills. - :param str message: (optional) The text of the message. - """ - self.message = message - - @classmethod - def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': - """Initialize a AgentAvailabilityMessage object from a json dictionary.""" - args = {} - if (message := _dict.get('message')) is not None: - args['message'] = message - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a AgentAvailabilityMessage object from 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') and self.message is not None: - _dict['message'] = self.message - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + Asynchronously export the action skill and dialog skill (if enabled) for the + assistant. Use this method to save all skill data so that you can import it to a + different assistant using the **Import skills** method. + A successful call to this method only initiates an asynchronous export. The + exported JSON data is not available until processing completes. + After the initial request is submitted, you can poll the status of the operation + by calling the same request again and checking the value of the **status** + property. If an error occurs (indicated by a **status** value of `Failed`), the + `status_description` property provides more information about the error, and the + `status_errors` property contains an array of error messages that caused the + failure. + When processing has completed, the request returns the exported JSON data. + Remember that the usual rate limits apply. - def __str__(self) -> str: - """Return a `str` version of this AgentAvailabilityMessage object.""" - return json.dumps(self.to_dict(), indent=2) + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SkillsExport` object + """ - def __eq__(self, other: 'AgentAvailabilityMessage') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='export_skills', + ) + headers.update(sdk_headers) - def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + params = { + 'version': self.version, + 'include_audit': include_audit, + } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -class AssistantCollection: - """ - AssistantCollection. + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_export'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) - :param List[AssistantData] assistants: An array of objects describing the - assistants associated with the instance. - :param Pagination pagination: The pagination data for the returned objects. For - more information about using pagination, see [Pagination](#pagination). - """ + response = self.send(request, **kwargs) + return response - def __init__( + def import_skills( self, - assistants: List['AssistantData'], - pagination: 'Pagination', - ) -> None: + assistant_id: str, + assistant_skills: List['SkillImport'], + assistant_state: 'AssistantState', + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ - Initialize a AssistantCollection object. + Import skills. - :param List[AssistantData] assistants: An array of objects describing the - assistants associated with the instance. - :param Pagination pagination: The pagination data for the returned objects. - For more information about using pagination, see [Pagination](#pagination). - """ - self.assistants = assistants - self.pagination = pagination + Asynchronously import skills into an existing assistant from a previously exported + file. + The request body for this method should contain the response data that was + received from a previous call to the **Export skills** method, without + modification. + A successful call to this method initiates an asynchronous import. The updated + skills belonging to the assistant are not available until processing completes. To + check the status of the asynchronous import operation, use the **Get status of + skills import** method. - @classmethod - def from_dict(cls, _dict: Dict) -> 'AssistantCollection': - """Initialize a AssistantCollection object from a json dictionary.""" - args = {} - if (assistants := _dict.get('assistants')) is not None: - args['assistants'] = [ - AssistantData.from_dict(v) for v in assistants - ] - else: - raise ValueError( - 'Required property \'assistants\' not present in AssistantCollection JSON' - ) - if (pagination := _dict.get('pagination')) is not None: - args['pagination'] = Pagination.from_dict(pagination) - else: - raise ValueError( - 'Required property \'pagination\' not present in AssistantCollection JSON' - ) - return cls(**args) + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param List[SkillImport] assistant_skills: An array of objects describing + the skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object + """ - @classmethod - def _from_dict(cls, _dict): - """Initialize a AssistantCollection object from a json dictionary.""" - return cls.from_dict(_dict) + if not assistant_id: + raise ValueError('assistant_id must be provided') + if assistant_skills is None: + raise ValueError('assistant_skills must be provided') + if assistant_state is None: + raise ValueError('assistant_state must be provided') + assistant_skills = [convert_model(x) for x in assistant_skills] + assistant_state = convert_model(assistant_state) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills', + ) + headers.update(sdk_headers) - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'assistants') and self.assistants is not None: - assistants_list = [] - for v in self.assistants: - if isinstance(v, dict): - assistants_list.append(v) - else: - assistants_list.append(v.to_dict()) - _dict['assistants'] = assistants_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination - else: - _dict['pagination'] = self.pagination.to_dict() - return _dict + params = { + 'version': self.version, + 'include_audit': include_audit, + } - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + data = { + 'assistant_skills': assistant_skills, + 'assistant_state': assistant_state, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - def __str__(self) -> str: - """Return a `str` version of this AssistantCollection object.""" - return json.dumps(self.to_dict(), indent=2) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def __eq__(self, other: 'AssistantCollection') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_import'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) - def __ne__(self, other: 'AssistantCollection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + response = self.send(request, **kwargs) + return response + def import_skills_status( + self, + assistant_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Get status of skills import. -class AssistantData: + Retrieve the status of an asynchronous import operation previously initiated by + using the **Import skills** method. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills_status', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_import/status'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + +class ListProvidersEnums: + """ + Enums for list_providers parameters. """ - AssistantData. - :param str assistant_id: (optional) The unique identifier of the assistant. - :param str name: (optional) The name of the assistant. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the assistant. This string - cannot contain carriage return, newline, or tab characters. - :param str language: The language of the assistant. - :param List[AssistantSkill] assistant_skills: (optional) An array of skill - references identifying the skills associated with the assistant. - :param List[EnvironmentReference] assistant_environments: (optional) An array of - objects describing the environments defined for the assistant. + class Sort(str, Enum): + """ + The attribute by which returned conversational skill providers will be sorted. To + reverse the sort order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class ListAssistantsEnums: + """ + Enums for list_assistants parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned assistants will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class ListEnvironmentsEnums: + """ + Enums for list_environments parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned environments will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class ListReleasesEnums: + """ + Enums for list_releases parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned workspaces will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class DownloadReleaseExportEnums: + """ + Enums for download_release_export parameters. + """ + + class Accept(str, Enum): + """ + The type of the response: application/json or application/octet-stream. + """ + + APPLICATION_JSON = 'application/json' + APPLICATION_OCTET_STREAM = 'application/octet-stream' + + +############################################################################## +# Models +############################################################################## + + +class AgentAvailabilityMessage: + """ + AgentAvailabilityMessage. + + :param str message: (optional) The text of the message. """ def __init__( self, - language: str, *, - assistant_id: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - assistant_skills: Optional[List['AssistantSkill']] = None, - assistant_environments: Optional[List['EnvironmentReference']] = None, + message: Optional[str] = None, ) -> None: """ - Initialize a AssistantData object. + Initialize a AgentAvailabilityMessage object. - :param str language: The language of the assistant. - :param str name: (optional) The name of the assistant. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the assistant. This - string cannot contain carriage return, newline, or tab characters. + :param str message: (optional) The text of the message. """ - self.assistant_id = assistant_id - self.name = name - self.description = description - self.language = language - self.assistant_skills = assistant_skills - self.assistant_environments = assistant_environments + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'AssistantData': - """Initialize a AssistantData object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': + """Initialize a AgentAvailabilityMessage object from a json dictionary.""" args = {} - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in AssistantData JSON' - ) - if (assistant_skills := _dict.get('assistant_skills')) is not None: - args['assistant_skills'] = [ - AssistantSkill.from_dict(v) for v in assistant_skills - ] - if (assistant_environments := - _dict.get('assistant_environments')) is not None: - args['assistant_environments'] = [ - EnvironmentReference.from_dict(v) - for v in assistant_environments - ] + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a AssistantData object from a json dictionary.""" + """Initialize a AgentAvailabilityMessage object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'assistant_skills') and getattr( - self, 'assistant_skills') is not None: - assistant_skills_list = [] - for v in getattr(self, 'assistant_skills'): - if isinstance(v, dict): - assistant_skills_list.append(v) - else: - assistant_skills_list.append(v.to_dict()) - _dict['assistant_skills'] = assistant_skills_list - if hasattr(self, 'assistant_environments') and getattr( - self, 'assistant_environments') is not None: - assistant_environments_list = [] - for v in getattr(self, 'assistant_environments'): - if isinstance(v, dict): - assistant_environments_list.append(v) - else: - assistant_environments_list.append(v.to_dict()) - _dict['assistant_environments'] = assistant_environments_list + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -2217,39 +2796,253 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this AssistantData object.""" + """Return a `str` version of this AgentAvailabilityMessage object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'AssistantData') -> bool: + def __eq__(self, other: 'AgentAvailabilityMessage') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'AssistantData') -> bool: + def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class AssistantSkill: +class AssistantCollection: """ - AssistantSkill. + AssistantCollection. - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. + :param List[AssistantData] assistants: An array of objects describing the + assistants associated with the instance. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__( self, - skill_id: str, - *, - type: Optional[str] = None, + assistants: List['AssistantData'], + pagination: 'Pagination', ) -> None: """ - Initialize a AssistantSkill object. + Initialize a AssistantCollection object. - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. + :param List[AssistantData] assistants: An array of objects describing the + assistants associated with the instance. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + self.assistants = assistants + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AssistantCollection': + """Initialize a AssistantCollection object from a json dictionary.""" + args = {} + if (assistants := _dict.get('assistants')) is not None: + args['assistants'] = [ + AssistantData.from_dict(v) for v in assistants + ] + else: + raise ValueError( + 'Required property \'assistants\' not present in AssistantCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in AssistantCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AssistantCollection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'assistants') and self.assistants is not None: + assistants_list = [] + for v in self.assistants: + if isinstance(v, dict): + assistants_list.append(v) + else: + assistants_list.append(v.to_dict()) + _dict['assistants'] = assistants_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.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 AssistantCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AssistantCollection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AssistantCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AssistantData: + """ + AssistantData. + + :param str assistant_id: (optional) The unique identifier of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This string + cannot contain carriage return, newline, or tab characters. + :param str language: The language of the assistant. + :param List[AssistantSkill] assistant_skills: (optional) An array of skill + references identifying the skills associated with the assistant. + :param List[EnvironmentReference] assistant_environments: (optional) An array of + objects describing the environments defined for the assistant. + """ + + def __init__( + self, + language: str, + *, + assistant_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + assistant_skills: Optional[List['AssistantSkill']] = None, + assistant_environments: Optional[List['EnvironmentReference']] = None, + ) -> None: + """ + Initialize a AssistantData object. + + :param str language: The language of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This + string cannot contain carriage return, newline, or tab characters. + """ + self.assistant_id = assistant_id + self.name = name + self.description = description + self.language = language + self.assistant_skills = assistant_skills + self.assistant_environments = assistant_environments + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AssistantData': + """Initialize a AssistantData object from a json dictionary.""" + args = {} + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in AssistantData JSON' + ) + if (assistant_skills := _dict.get('assistant_skills')) is not None: + args['assistant_skills'] = [ + AssistantSkill.from_dict(v) for v in assistant_skills + ] + if (assistant_environments := + _dict.get('assistant_environments')) is not None: + args['assistant_environments'] = [ + EnvironmentReference.from_dict(v) + for v in assistant_environments + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AssistantData object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'assistant_skills') and getattr( + self, 'assistant_skills') is not None: + assistant_skills_list = [] + for v in getattr(self, 'assistant_skills'): + if isinstance(v, dict): + assistant_skills_list.append(v) + else: + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, 'assistant_environments') and getattr( + self, 'assistant_environments') is not None: + assistant_environments_list = [] + for v in getattr(self, 'assistant_environments'): + if isinstance(v, dict): + assistant_environments_list.append(v) + else: + assistant_environments_list.append(v.to_dict()) + _dict['assistant_environments'] = assistant_environments_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this AssistantData object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AssistantData') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'AssistantData') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AssistantSkill: + """ + AssistantSkill. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + """ + + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + ) -> None: + """ + Initialize a AssistantSkill object. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. """ self.skill_id = skill_id self.type = type @@ -3001,54 +3794,323 @@ def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: return not self == other -class DialogLogMessage: +class CreateAssistantReleaseImportResponse: """ - Dialog log message details. - - :param str level: The severity of the log message. - :param str message: The text of the log message. - :param str code: A code that indicates the category to which the error message + CreateAssistantReleaseImportResponse. + + :param str status: (optional) The current status of the artifact import process: + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import artifact is underway and + not yet completed. + :param str task_id: (optional) A unique identifier for a background asynchronous + task that is executing or has executed the operation. + :param str assistant_id: (optional) The ID of the assistant to which the release belongs. - :param LogMessageSource source: (optional) An object that identifies the dialog - element that generated the error message. + :param List[str] skill_impact_in_draft: (optional) An array of skill types in + the draft environment which will be overridden with skills from the artifact + being imported. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. """ def __init__( self, - level: str, - message: str, - code: str, *, - source: Optional['LogMessageSource'] = None, + status: Optional[str] = None, + task_id: Optional[str] = None, + assistant_id: Optional[str] = None, + skill_impact_in_draft: Optional[List[str]] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, ) -> None: """ - Initialize a DialogLogMessage object. + Initialize a CreateAssistantReleaseImportResponse object. - :param str level: The severity of the log message. - :param str message: The text of the log message. - :param str code: A code that indicates the category to which the error - message belongs. - :param LogMessageSource source: (optional) An object that identifies the - dialog element that generated the error message. + :param List[str] skill_impact_in_draft: (optional) An array of skill types + in the draft environment which will be overridden with skills from the + artifact being imported. """ - self.level = level - self.message = message - self.code = code - self.source = source + self.status = status + self.task_id = task_id + self.assistant_id = assistant_id + self.skill_impact_in_draft = skill_impact_in_draft + self.created = created + self.updated = updated @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': - """Initialize a DialogLogMessage object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CreateAssistantReleaseImportResponse': + """Initialize a CreateAssistantReleaseImportResponse object from a json dictionary.""" args = {} - if (level := _dict.get('level')) is not None: - args['level'] = level - else: - raise ValueError( - 'Required property \'level\' not present in DialogLogMessage JSON' - ) - if (message := _dict.get('message')) is not None: - args['message'] = message - else: + if (status := _dict.get('status')) is not None: + args['status'] = status + if (task_id := _dict.get('task_id')) is not None: + args['task_id'] = task_id + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (skill_impact_in_draft := + _dict.get('skill_impact_in_draft')) is not None: + args['skill_impact_in_draft'] = skill_impact_in_draft + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateAssistantReleaseImportResponse object from 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 getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'task_id') and getattr(self, 'task_id') is not None: + _dict['task_id'] = getattr(self, 'task_id') + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'skill_impact_in_draft' + ) and self.skill_impact_in_draft is not None: + _dict['skill_impact_in_draft'] = self.skill_impact_in_draft + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + 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 CreateAssistantReleaseImportResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CreateAssistantReleaseImportResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CreateAssistantReleaseImportResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the artifact import process: + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import artifact is underway and + not yet completed. + """ + + FAILED = 'Failed' + PROCESSING = 'Processing' + + class SkillImpactInDraftEnum(str, Enum): + """ + The type of the skill in the draft environment. + """ + + ACTION = 'action' + DIALOG = 'dialog' + + +class CreateReleaseExportWithStatusErrors: + """ + CreateReleaseExportWithStatusErrors. + + :param str status: (optional) The current status of the release export creation + process: + - **Available**: The release export package is available for download. + - **Failed**: The asynchronous release export package creation process has + failed. + - **Processing**: An asynchronous operation to create the release export + package is underway and not yet completed. + :param str task_id: (optional) A unique identifier for a background asynchronous + task that is executing or has executed the operation. + :param str assistant_id: (optional) The ID of the assistant to which the release + belongs. + :param str release: (optional) The name of the release. The name is the version + number (an integer), returned as a string. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + """ + + def __init__( + self, + *, + status: Optional[str] = None, + task_id: Optional[str] = None, + assistant_id: Optional[str] = None, + release: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + ) -> None: + """ + Initialize a CreateReleaseExportWithStatusErrors object. + + """ + self.status = status + self.task_id = task_id + self.assistant_id = assistant_id + self.release = release + self.created = created + self.updated = updated + self.status_errors = status_errors + self.status_description = status_description + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CreateReleaseExportWithStatusErrors': + """Initialize a CreateReleaseExportWithStatusErrors object from a json dictionary.""" + args = {} + if (status := _dict.get('status')) is not None: + args['status'] = status + if (task_id := _dict.get('task_id')) is not None: + args['task_id'] = task_id + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (release := _dict.get('release')) is not None: + args['release'] = release + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateReleaseExportWithStatusErrors object from 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 getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'task_id') and getattr(self, 'task_id') is not None: + _dict['task_id'] = getattr(self, 'task_id') + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'release') and getattr(self, 'release') is not None: + _dict['release'] = getattr(self, 'release') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + 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 CreateReleaseExportWithStatusErrors object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CreateReleaseExportWithStatusErrors') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'CreateReleaseExportWithStatusErrors') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the release export creation process: + - **Available**: The release export package is available for download. + - **Failed**: The asynchronous release export package creation process has + failed. + - **Processing**: An asynchronous operation to create the release export package + is underway and not yet completed. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class DialogLogMessage: + """ + Dialog log message details. + + :param str level: The severity of the log message. + :param str message: The text of the log message. + :param str code: A code that indicates the category to which the error message + belongs. + :param LogMessageSource source: (optional) An object that identifies the dialog + element that generated the error message. + """ + + def __init__( + self, + level: str, + message: str, + code: str, + *, + source: Optional['LogMessageSource'] = None, + ) -> None: + """ + Initialize a DialogLogMessage object. + + :param str level: The severity of the log message. + :param str message: The text of the log message. + :param str code: A code that indicates the category to which the error + message belongs. + :param LogMessageSource source: (optional) An object that identifies the + dialog element that generated the error message. + """ + self.level = level + self.message = message + self.code = code + self.source = source + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': + """Initialize a DialogLogMessage object from a json dictionary.""" + args = {} + if (level := _dict.get('level')) is not None: + args['level'] = level + else: + raise ValueError( + 'Required property \'level\' not present in DialogLogMessage JSON' + ) + if (message := _dict.get('message')) is not None: + args['message'] = message + else: raise ValueError( 'Required property \'message\' not present in DialogLogMessage JSON' ) @@ -5776,6 +6838,8 @@ class MessageContextSkillSystem: subsequent message request, you can return to an earlier point in the conversation. If you are using stateful sessions, you can also use a stored state value to restore a paused conversation whose session is expired. + + This type supports additional properties of type object. For internal use only. """ # The set of defined properties for the class @@ -5785,7 +6849,7 @@ def __init__( self, *, state: Optional[str] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a MessageContextSkillSystem object. @@ -5795,11 +6859,20 @@ def __init__( of a subsequent message request, you can return to an earlier point in the conversation. If you are using stateful sessions, you can also use a stored state value to restore a paused conversation whose session is expired. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) For internal use only. """ self.state = state - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in MessageContextSkillSystem._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': @@ -5807,8 +6880,13 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': args = {} if (state := _dict.get('state')) is not None: args['state'] = state - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -5821,11 +6899,11 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'state') and self.state is not None: _dict['state'] = self.state - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -5833,27 +6911,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" + """Return the additional properties from this instance of MessageContextSkillSystem in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties + """Set a dictionary of additional properties in this instance of MessageContextSkillSystem""" + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in MessageContextSkillSystem._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in MessageContextSkillSystem._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this MessageContextSkillSystem object.""" @@ -6918,97 +8002,45 @@ def __ne__(self, other: 'MessageOutputSpelling') -> bool: return not self == other -class Pagination: +class Metadata: """ - The pagination data for the returned objects. For more information about using - pagination, see [Pagination](#pagination). + Contains meta-information about the item(s) being streamed. - :param str refresh_url: The URL that will return the same page of results. - :param str next_url: (optional) The URL that will return the next page of - results. - :param int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the current - page. - :param int matched: (optional) Reserved for future use. - :param str refresh_cursor: (optional) A token identifying the current page of - results. - :param str next_cursor: (optional) A token identifying the next page of results. + :param int id: (optional) Identifies the index and sequence of the current + streamed response item. """ def __init__( self, - refresh_url: str, *, - next_url: Optional[str] = None, - total: Optional[int] = None, - matched: Optional[int] = None, - refresh_cursor: Optional[str] = None, - next_cursor: Optional[str] = None, + id: Optional[int] = None, ) -> None: """ - Initialize a Pagination object. + Initialize a Metadata object. - :param str refresh_url: The URL that will return the same page of results. - :param str next_url: (optional) The URL that will return the next page of - results. - :param int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the - current page. - :param int matched: (optional) Reserved for future use. - :param str refresh_cursor: (optional) A token identifying the current page - of results. - :param str next_cursor: (optional) A token identifying the next page of - results. + :param int id: (optional) Identifies the index and sequence of the current + streamed response item. """ - self.refresh_url = refresh_url - self.next_url = next_url - self.total = total - self.matched = matched - self.refresh_cursor = refresh_cursor - self.next_cursor = next_cursor + self.id = id @classmethod - def from_dict(cls, _dict: Dict) -> 'Pagination': - """Initialize a Pagination object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Metadata': + """Initialize a Metadata object from a json dictionary.""" args = {} - if (refresh_url := _dict.get('refresh_url')) is not None: - args['refresh_url'] = refresh_url - else: - raise ValueError( - 'Required property \'refresh_url\' not present in Pagination JSON' - ) - if (next_url := _dict.get('next_url')) is not None: - args['next_url'] = next_url - if (total := _dict.get('total')) is not None: - args['total'] = total - if (matched := _dict.get('matched')) is not None: - args['matched'] = matched - if (refresh_cursor := _dict.get('refresh_cursor')) is not None: - args['refresh_cursor'] = refresh_cursor - if (next_cursor := _dict.get('next_cursor')) is not None: - args['next_cursor'] = next_cursor + if (id := _dict.get('id')) is not None: + args['id'] = id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Pagination object from a json dictionary.""" + """Initialize a Metadata object from 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: - _dict['refresh_url'] = self.refresh_url - if hasattr(self, 'next_url') and self.next_url is not None: - _dict['next_url'] = self.next_url - if hasattr(self, 'total') and self.total is not None: - _dict['total'] = self.total - if hasattr(self, 'matched') and self.matched is not None: - _dict['matched'] = self.matched - if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: - _dict['refresh_cursor'] = self.refresh_cursor - if hasattr(self, 'next_cursor') and self.next_cursor is not None: - _dict['next_cursor'] = self.next_cursor + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id return _dict def _to_dict(self): @@ -7016,35 +8048,41 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Pagination object.""" + """Return a `str` version of this Metadata object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Pagination') -> bool: + def __eq__(self, other: 'Metadata') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Pagination') -> bool: + def __ne__(self, other: 'Metadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Release: +class MonitorAssistantReleaseImportArtifactResponse: """ - Release. - - :param str release: (optional) The name of the release. The name is the version - number (an integer), returned as a string. - :param str description: (optional) The description of the release. - :param List[EnvironmentReference] environment_references: (optional) An array of - objects describing the environments where this release has been deployed. - :param ReleaseContent content: (optional) An object identifying the versionable - content objects (such as skill snapshots) that are included in the release. - :param str status: (optional) The current status of the release: - - **Available**: The release is available for deployment. - - **Failed**: An asynchronous publish operation has failed. - - **Processing**: An asynchronous publish operation has not yet completed. + MonitorAssistantReleaseImportArtifactResponse. + + :param str status: (optional) The current status of the release import process: + - **Completed**: The artifact import has completed. + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import the artifact is underway + and not yet completed. + :param str task_id: (optional) A unique identifier for a background asynchronous + task that is executing or has executed the operation. + :param str assistant_id: (optional) The ID of the assistant to which the release + belongs. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param List[str] skill_impact_in_draft: (optional) An array of skill types in + the draft environment which will be overridden with skills from the artifact + being imported. :param datetime created: (optional) The timestamp for creation of the object. :param datetime updated: (optional) The timestamp for the most recent update to the object. @@ -7053,45 +8091,52 @@ class Release: def __init__( self, *, - release: Optional[str] = None, - description: Optional[str] = None, - environment_references: Optional[List['EnvironmentReference']] = None, - content: Optional['ReleaseContent'] = None, status: Optional[str] = None, + task_id: Optional[str] = None, + assistant_id: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + skill_impact_in_draft: Optional[List[str]] = None, created: Optional[datetime] = None, updated: Optional[datetime] = None, ) -> None: """ - Initialize a Release object. + Initialize a MonitorAssistantReleaseImportArtifactResponse object. - :param str description: (optional) The description of the release. + :param List[str] skill_impact_in_draft: (optional) An array of skill types + in the draft environment which will be overridden with skills from the + artifact being imported. """ - self.release = release - self.description = description - self.environment_references = environment_references - self.content = content self.status = status + self.task_id = task_id + self.assistant_id = assistant_id + self.status_errors = status_errors + self.status_description = status_description + self.skill_impact_in_draft = skill_impact_in_draft self.created = created self.updated = updated @classmethod - def from_dict(cls, _dict: Dict) -> 'Release': - """Initialize a Release object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MonitorAssistantReleaseImportArtifactResponse': + """Initialize a MonitorAssistantReleaseImportArtifactResponse object from a json dictionary.""" args = {} - if (release := _dict.get('release')) is not None: - args['release'] = release - if (description := _dict.get('description')) is not None: - args['description'] = description - if (environment_references := - _dict.get('environment_references')) is not None: - args['environment_references'] = [ - EnvironmentReference.from_dict(v) - for v in environment_references - ] - if (content := _dict.get('content')) is not None: - args['content'] = ReleaseContent.from_dict(content) if (status := _dict.get('status')) is not None: args['status'] = status + if (task_id := _dict.get('task_id')) is not None: + args['task_id'] = task_id + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (skill_impact_in_draft := + _dict.get('skill_impact_in_draft')) is not None: + args['skill_impact_in_draft'] = skill_impact_in_draft if (created := _dict.get('created')) is not None: args['created'] = string_to_datetime(created) if (updated := _dict.get('updated')) is not None: @@ -7100,32 +8145,34 @@ def from_dict(cls, _dict: Dict) -> 'Release': @classmethod def _from_dict(cls, _dict): - """Initialize a Release object from a json dictionary.""" + """Initialize a MonitorAssistantReleaseImportArtifactResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'release') and getattr(self, 'release') is not None: - _dict['release'] = getattr(self, 'release') - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'environment_references') and getattr( - self, 'environment_references') is not None: - environment_references_list = [] - for v in getattr(self, 'environment_references'): - if isinstance(v, dict): - environment_references_list.append(v) - else: - environment_references_list.append(v.to_dict()) - _dict['environment_references'] = environment_references_list - if hasattr(self, 'content') and getattr(self, 'content') is not None: - if isinstance(getattr(self, 'content'), dict): - _dict['content'] = getattr(self, 'content') - else: - _dict['content'] = getattr(self, 'content').to_dict() if hasattr(self, 'status') and getattr(self, 'status') is not None: _dict['status'] = getattr(self, 'status') + if hasattr(self, 'task_id') and getattr(self, 'task_id') is not None: + _dict['task_id'] = getattr(self, 'task_id') + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'skill_impact_in_draft' + ) and self.skill_impact_in_draft is not None: + _dict['skill_impact_in_draft'] = self.skill_impact_in_draft if hasattr(self, 'created') and getattr(self, 'created') is not None: _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'updated') and getattr(self, 'updated') is not None: @@ -7137,162 +8184,208 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Release object.""" + """Return a `str` version of this MonitorAssistantReleaseImportArtifactResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Release') -> bool: + def __eq__(self, + other: 'MonitorAssistantReleaseImportArtifactResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Release') -> bool: + def __ne__(self, + other: 'MonitorAssistantReleaseImportArtifactResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class StatusEnum(str, Enum): """ - The current status of the release: - - **Available**: The release is available for deployment. - - **Failed**: An asynchronous publish operation has failed. - - **Processing**: An asynchronous publish operation has not yet completed. + The current status of the release import process: + - **Completed**: The artifact import has completed. + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import the artifact is underway + and not yet completed. """ - AVAILABLE = 'Available' + COMPLETED = 'Completed' FAILED = 'Failed' PROCESSING = 'Processing' + class SkillImpactInDraftEnum(str, Enum): + """ + The type of the skill in the draft environment. + """ -class ReleaseCollection: + ACTION = 'action' + DIALOG = 'dialog' + + +class Pagination: """ - ReleaseCollection. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). - :param List[Release] releases: An array of objects describing the releases - associated with an assistant. - :param Pagination pagination: The pagination data for the returned objects. For - more information about using pagination, see [Pagination](#pagination). + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the current + page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page of + results. + :param str next_cursor: (optional) A token identifying the next page of results. """ def __init__( self, - releases: List['Release'], - pagination: 'Pagination', + refresh_url: str, + *, + next_url: Optional[str] = None, + total: Optional[int] = None, + matched: Optional[int] = None, + refresh_cursor: Optional[str] = None, + next_cursor: Optional[str] = None, ) -> None: """ - Initialize a ReleaseCollection object. + Initialize a Pagination object. - :param List[Release] releases: An array of objects describing the releases - associated with an assistant. - :param Pagination pagination: The pagination data for the returned objects. - For more information about using pagination, see [Pagination](#pagination). + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the + current page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page + of results. + :param str next_cursor: (optional) A token identifying the next page of + results. """ - self.releases = releases - self.pagination = pagination + self.refresh_url = refresh_url + self.next_url = next_url + self.total = total + self.matched = matched + self.refresh_cursor = refresh_cursor + self.next_cursor = next_cursor @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': - """Initialize a ReleaseCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Pagination': + """Initialize a Pagination object from a json dictionary.""" args = {} - if (releases := _dict.get('releases')) is not None: - args['releases'] = [Release.from_dict(v) for v in releases] - else: - raise ValueError( - 'Required property \'releases\' not present in ReleaseCollection JSON' - ) - if (pagination := _dict.get('pagination')) is not None: - args['pagination'] = Pagination.from_dict(pagination) + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url else: raise ValueError( - 'Required property \'pagination\' not present in ReleaseCollection JSON' + 'Required property \'refresh_url\' not present in Pagination JSON' ) + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (total := _dict.get('total')) is not None: + args['total'] = total + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (refresh_cursor := _dict.get('refresh_cursor')) is not None: + args['refresh_cursor'] = refresh_cursor + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseCollection object from a json dictionary.""" + """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, 'releases') and self.releases is not None: - releases_list = [] - for v in self.releases: - if isinstance(v, dict): - releases_list.append(v) - else: - releases_list.append(v.to_dict()) - _dict['releases'] = releases_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination - else: - _dict['pagination'] = self.pagination.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 ReleaseCollection object.""" + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'total') and self.total is not None: + _dict['total'] = self.total + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: + _dict['refresh_cursor'] = self.refresh_cursor + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor + 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 Pagination object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseCollection') -> bool: + 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: 'ReleaseCollection') -> bool: + def __ne__(self, other: 'Pagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ReleaseContent: +class ProviderAuthenticationOAuth2: """ - An object identifying the versionable content objects (such as skill snapshots) that - are included in the release. + Non-private settings for oauth2 authentication. - :param List[ReleaseSkill] skills: (optional) The skill snapshots that are - included in the release. + :param str preferred_flow: (optional) The preferred "flow" or "grant type" for + the API client to fetch an access token from the authorization server. + :param ProviderAuthenticationOAuth2Flows flows: (optional) Scenarios performed + by the API client to fetch an access token from the authorization server. """ def __init__( self, *, - skills: Optional[List['ReleaseSkill']] = None, + preferred_flow: Optional[str] = None, + flows: Optional['ProviderAuthenticationOAuth2Flows'] = None, ) -> None: """ - Initialize a ReleaseContent object. + Initialize a ProviderAuthenticationOAuth2 object. + :param str preferred_flow: (optional) The preferred "flow" or "grant type" + for the API client to fetch an access token from the authorization server. + :param ProviderAuthenticationOAuth2Flows flows: (optional) Scenarios + performed by the API client to fetch an access token from the authorization + server. """ - self.skills = skills + self.preferred_flow = preferred_flow + self.flows = flows @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseContent': - """Initialize a ReleaseContent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderAuthenticationOAuth2': + """Initialize a ProviderAuthenticationOAuth2 object from a json dictionary.""" args = {} - if (skills := _dict.get('skills')) is not None: - args['skills'] = [ReleaseSkill.from_dict(v) for v in skills] + if (preferred_flow := _dict.get('preferred_flow')) is not None: + args['preferred_flow'] = preferred_flow + if (flows := _dict.get('flows')) is not None: + args['flows'] = flows return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseContent object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2 object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'skills') and getattr(self, 'skills') is not None: - skills_list = [] - for v in getattr(self, 'skills'): - if isinstance(v, dict): - skills_list.append(v) - else: - skills_list.append(v.to_dict()) - _dict['skills'] = skills_list + if hasattr(self, 'preferred_flow') and self.preferred_flow is not None: + _dict['preferred_flow'] = self.preferred_flow + if hasattr(self, 'flows') and self.flows is not None: + if isinstance(self.flows, dict): + _dict['flows'] = self.flows + else: + _dict['flows'] = self.flows.to_dict() return _dict def _to_dict(self): @@ -7300,79 +8393,98 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseContent object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2 object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseContent') -> bool: + def __eq__(self, other: 'ProviderAuthenticationOAuth2') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ReleaseContent') -> bool: + def __ne__(self, other: 'ProviderAuthenticationOAuth2') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class PreferredFlowEnum(str, Enum): + """ + The preferred "flow" or "grant type" for the API client to fetch an access token + from the authorization server. + """ -class ReleaseSkill: + PASSWORD = 'password' + CLIENT_CREDENTIALS = 'client_credentials' + AUTHORIZATION_CODE = 'authorization_code' + CUSTOM_FLOW_NAME = '<$custom_flow_name>' + + +class ProviderAuthenticationOAuth2Flows: """ - ReleaseSkill. + Scenarios performed by the API client to fetch an access token from the authorization + server. - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. - :param str snapshot: (optional) The name of the skill snapshot that is saved as - part of the release (for example, `draft` or `1`). + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderAuthenticationOAuth2Flows object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password', + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials', + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode' + ])) + raise Exception(msg) + + +class ProviderAuthenticationOAuth2PasswordUsername: + """ + The username for oauth2 authentication when the preferred flow is "password". + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ def __init__( self, - skill_id: str, *, type: Optional[str] = None, - snapshot: Optional[str] = None, + value: Optional[str] = None, ) -> None: """ - Initialize a ReleaseSkill object. + Initialize a ProviderAuthenticationOAuth2PasswordUsername object. - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. - :param str snapshot: (optional) The name of the skill snapshot that is - saved as part of the release (for example, `draft` or `1`). + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ - self.skill_id = skill_id self.type = type - self.snapshot = snapshot + self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': - """Initialize a ReleaseSkill object from a json dictionary.""" + def from_dict( + cls, _dict: Dict) -> 'ProviderAuthenticationOAuth2PasswordUsername': + """Initialize a ProviderAuthenticationOAuth2PasswordUsername object from a json dictionary.""" args = {} - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - else: - raise ValueError( - 'Required property \'skill_id\' not present in ReleaseSkill JSON' - ) if (type := _dict.get('type')) is not None: args['type'] = type - if (snapshot := _dict.get('snapshot')) is not None: - args['snapshot'] = snapshot + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseSkill object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2PasswordUsername object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'skill_id') and self.skill_id is not None: - _dict['skill_id'] = self.skill_id if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value return _dict def _to_dict(self): @@ -7380,89 +8492,74 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseSkill object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2PasswordUsername object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseSkill') -> bool: + def __eq__(self, + other: 'ProviderAuthenticationOAuth2PasswordUsername') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ReleaseSkill') -> bool: + def __ne__(self, + other: 'ProviderAuthenticationOAuth2PasswordUsername') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TypeEnum(str, Enum): """ - The type of the skill. + The type of property observed in "value". """ - DIALOG = 'dialog' - ACTION = 'action' - SEARCH = 'search' + VALUE = 'value' -class RequestAnalytics: +class ProviderAuthenticationTypeAndValue: """ - An optional object containing analytics data. Currently, this data is used only for - events sent to the Segment extension. + ProviderAuthenticationTypeAndValue. - :param str browser: (optional) The browser that was used to send the message - that triggered the event. - :param str device: (optional) The type of device that was used to send the - message that triggered the event. - :param str page_url: (optional) The URL of the web page that was used to send - the message that triggered the event. + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ def __init__( self, *, - browser: Optional[str] = None, - device: Optional[str] = None, - page_url: Optional[str] = None, + type: Optional[str] = None, + value: Optional[str] = None, ) -> None: """ - Initialize a RequestAnalytics object. + Initialize a ProviderAuthenticationTypeAndValue object. - :param str browser: (optional) The browser that was used to send the - message that triggered the event. - :param str device: (optional) The type of device that was used to send the - message that triggered the event. - :param str page_url: (optional) The URL of the web page that was used to - send the message that triggered the event. + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ - self.browser = browser - self.device = device - self.page_url = page_url + self.type = type + self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': - """Initialize a RequestAnalytics object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderAuthenticationTypeAndValue': + """Initialize a ProviderAuthenticationTypeAndValue object from a json dictionary.""" args = {} - if (browser := _dict.get('browser')) is not None: - args['browser'] = browser - if (device := _dict.get('device')) is not None: - args['device'] = device - if (page_url := _dict.get('pageUrl')) is not None: - args['page_url'] = page_url + if (type := _dict.get('type')) is not None: + args['type'] = type + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RequestAnalytics object from a json dictionary.""" + """Initialize a ProviderAuthenticationTypeAndValue object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'browser') and self.browser is not None: - _dict['browser'] = self.browser - if hasattr(self, 'device') and self.device is not None: - _dict['device'] = self.device - if hasattr(self, 'page_url') and self.page_url is not None: - _dict['pageUrl'] = self.page_url + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value return _dict def _to_dict(self): @@ -7470,58 +8567,100 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RequestAnalytics object.""" + """Return a `str` version of this ProviderAuthenticationTypeAndValue object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RequestAnalytics') -> bool: + def __eq__(self, other: 'ProviderAuthenticationTypeAndValue') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RequestAnalytics') -> bool: + def __ne__(self, other: 'ProviderAuthenticationTypeAndValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of property observed in "value". + """ + + VALUE = 'value' -class ResponseGenericChannel: + +class ProviderCollection: """ - ResponseGenericChannel. + ProviderCollection. - :param str channel: (optional) A channel for which the response is intended. + :param List[ProviderResponse] conversational_skill_providers: An array of + objects describing the conversational skill providers associated with the + instance. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__( self, - *, - channel: Optional[str] = None, + conversational_skill_providers: List['ProviderResponse'], + pagination: 'Pagination', ) -> None: """ - Initialize a ResponseGenericChannel object. + Initialize a ProviderCollection object. - :param str channel: (optional) A channel for which the response is - intended. + :param List[ProviderResponse] conversational_skill_providers: An array of + objects describing the conversational skill providers associated with the + instance. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - self.channel = channel + self.conversational_skill_providers = conversational_skill_providers + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': - """Initialize a ResponseGenericChannel object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderCollection': + """Initialize a ProviderCollection object from a json dictionary.""" args = {} - if (channel := _dict.get('channel')) is not None: - args['channel'] = channel + if (conversational_skill_providers := + _dict.get('conversational_skill_providers')) is not None: + args['conversational_skill_providers'] = [ + ProviderResponse.from_dict(v) + for v in conversational_skill_providers + ] + else: + raise ValueError( + 'Required property \'conversational_skill_providers\' not present in ProviderCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in ProviderCollection JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ResponseGenericChannel object from a json dictionary.""" + """Initialize a ProviderCollection object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'channel') and self.channel is not None: - _dict['channel'] = self.channel + if hasattr(self, 'conversational_skill_providers' + ) and self.conversational_skill_providers is not None: + conversational_skill_providers_list = [] + for v in self.conversational_skill_providers: + if isinstance(v, dict): + conversational_skill_providers_list.append(v) + else: + conversational_skill_providers_list.append(v.to_dict()) + _dict[ + 'conversational_skill_providers'] = conversational_skill_providers_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -7529,194 +8668,65 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ResponseGenericChannel object.""" + """Return a `str` version of this ProviderCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ResponseGenericChannel') -> bool: + def __eq__(self, other: 'ProviderCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'ResponseGenericChannel') -> bool: + def __ne__(self, other: 'ProviderCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntity: +class ProviderPrivate: """ - The entity value that was recognized in the user input. + Private information of the provider. - :param str entity: An entity detected in the input. - :param List[int] location: (optional) An array of zero-based character offsets - that indicate where the detected entity values begin and end in the input text. - :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 - confidence in the recognized entity. - :param List[CaptureGroup] groups: (optional) The recognized capture groups for - the entity, as defined by the entity pattern. - :param RuntimeEntityInterpretation interpretation: (optional) An object - containing detailed information about the entity recognized in the user input. - This property is included only if the new system entities are enabled for the - skill. - For more information about how the new system entities are interpreted, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). - :param List[RuntimeEntityAlternative] alternatives: (optional) An array of - possible alternative values that the user might have intended instead of the - value returned in the **value** property. This property is returned only for - `@sys-time` and `@sys-date` entities when the user's input is ambiguous. - This property is included only if the new system entities are enabled for the - skill. - :param RuntimeEntityRole role: (optional) An object describing the role played - by a system entity that is specifies the beginning or end of a range recognized - in the user input. This property is included only if the new system entities are - enabled for the skill. - :param str skill: (optional) The skill that recognized the entity value. - Currently, the only possible values are `main skill` for the dialog skill (if - enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and an - action skill. + :param ProviderPrivateAuthentication authentication: Private authentication + information of the provider. """ def __init__( self, - entity: str, - value: str, - *, - location: Optional[List[int]] = None, - confidence: Optional[float] = None, - groups: Optional[List['CaptureGroup']] = None, - interpretation: Optional['RuntimeEntityInterpretation'] = None, - alternatives: Optional[List['RuntimeEntityAlternative']] = None, - role: Optional['RuntimeEntityRole'] = None, - skill: Optional[str] = None, + authentication: 'ProviderPrivateAuthentication', ) -> None: """ - Initialize a RuntimeEntity object. + Initialize a ProviderPrivate object. - :param str entity: An entity detected in the input. - :param str value: The term in the input text that was recognized as an - entity value. - :param List[int] location: (optional) An array of zero-based character - offsets that indicate where the detected entity values begin and end in the - input text. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized entity. - :param List[CaptureGroup] groups: (optional) The recognized capture groups - for the entity, as defined by the entity pattern. - :param RuntimeEntityInterpretation interpretation: (optional) An object - containing detailed information about the entity recognized in the user - input. This property is included only if the new system entities are - enabled for the skill. - For more information about how the new system entities are interpreted, see - the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). - :param List[RuntimeEntityAlternative] alternatives: (optional) An array of - possible alternative values that the user might have intended instead of - the value returned in the **value** property. This property is returned - only for `@sys-time` and `@sys-date` entities when the user's input is - ambiguous. - This property is included only if the new system entities are enabled for - the skill. - :param RuntimeEntityRole role: (optional) An object describing the role - played by a system entity that is specifies the beginning or end of a range - recognized in the user input. This property is included only if the new - system entities are enabled for the skill. - :param str skill: (optional) The skill that recognized the entity value. - Currently, the only possible values are `main skill` for the dialog skill - (if enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and - an action skill. + :param ProviderPrivateAuthentication authentication: Private authentication + information of the provider. """ - self.entity = entity - self.location = location - self.value = value - self.confidence = confidence - self.groups = groups - self.interpretation = interpretation - self.alternatives = alternatives - self.role = role - self.skill = skill + self.authentication = authentication @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': - """Initialize a RuntimeEntity object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderPrivate': + """Initialize a ProviderPrivate object from a json dictionary.""" args = {} - if (entity := _dict.get('entity')) is not None: - args['entity'] = entity + if (authentication := _dict.get('authentication')) is not None: + args['authentication'] = authentication else: raise ValueError( - 'Required property \'entity\' not present in RuntimeEntity JSON' + 'Required property \'authentication\' not present in ProviderPrivate JSON' ) - if (location := _dict.get('location')) is not None: - args['location'] = location - if (value := _dict.get('value')) is not None: - args['value'] = value - else: - raise ValueError( - 'Required property \'value\' not present in RuntimeEntity JSON') - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (groups := _dict.get('groups')) is not None: - args['groups'] = [CaptureGroup.from_dict(v) for v in groups] - if (interpretation := _dict.get('interpretation')) is not None: - args['interpretation'] = RuntimeEntityInterpretation.from_dict( - interpretation) - if (alternatives := _dict.get('alternatives')) is not None: - args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(v) for v in alternatives - ] - if (role := _dict.get('role')) is not None: - args['role'] = RuntimeEntityRole.from_dict(role) - if (skill := _dict.get('skill')) is not None: - args['skill'] = skill return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntity object from a json dictionary.""" + """Initialize a ProviderPrivate object from 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: - _dict['entity'] = self.entity - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'groups') and self.groups is not None: - groups_list = [] - for v in self.groups: - if isinstance(v, dict): - groups_list.append(v) - else: - groups_list.append(v.to_dict()) - _dict['groups'] = groups_list - if hasattr(self, 'interpretation') and self.interpretation is not None: - if isinstance(self.interpretation, dict): - _dict['interpretation'] = self.interpretation - else: - _dict['interpretation'] = self.interpretation.to_dict() - if hasattr(self, 'alternatives') and self.alternatives is not None: - alternatives_list = [] - for v in self.alternatives: - if isinstance(v, dict): - alternatives_list.append(v) - else: - alternatives_list.append(v.to_dict()) - _dict['alternatives'] = alternatives_list - if hasattr(self, 'role') and self.role is not None: - if isinstance(self.role, dict): - _dict['role'] = self.role + if hasattr(self, 'authentication') and self.authentication is not None: + if isinstance(self.authentication, dict): + _dict['authentication'] = self.authentication else: - _dict['role'] = self.role.to_dict() - if hasattr(self, 'skill') and self.skill is not None: - _dict['skill'] = self.skill + _dict['authentication'] = self.authentication.to_dict() return _dict def _to_dict(self): @@ -7724,69 +8734,108 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntity object.""" + """Return a `str` version of this ProviderPrivate object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntity') -> bool: + def __eq__(self, other: 'ProviderPrivate') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntity') -> bool: + def __ne__(self, other: 'ProviderPrivate') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityAlternative: +class ProviderPrivateAuthentication: """ - An alternative value for the recognized entity. + Private authentication information of the provider. - :param str value: (optional) The entity value that was recognized in the user - input. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized entity. + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderPrivateAuthentication object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderPrivateAuthenticationBearerFlow', + 'ProviderPrivateAuthenticationBasicFlow', + 'ProviderPrivateAuthenticationOAuth2Flow' + ])) + raise Exception(msg) + + +class ProviderPrivateAuthenticationOAuth2FlowFlows: + """ + Scenarios performed by the API client to fetch an access token from the authorization + server. + + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlows object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password', + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials', + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode' + ])) + raise Exception(msg) + + +class ProviderPrivateAuthenticationOAuth2PasswordPassword: + """ + The password for oauth2 authentication when the preferred flow is "password". + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ def __init__( self, *, + type: Optional[str] = None, value: Optional[str] = None, - confidence: Optional[float] = None, ) -> None: """ - Initialize a RuntimeEntityAlternative object. + Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object. - :param str value: (optional) The entity value that was recognized in the - user input. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized entity. + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ + self.type = type self.value = value - self.confidence = confidence @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2PasswordPassword': + """Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object from a json dictionary.""" args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type if (value := _dict.get('value')) is not None: args['value'] = value - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object from 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, 'value') and self.value is not None: _dict['value'] = self.value - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence return _dict def _to_dict(self): @@ -7794,103 +8843,1752 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityAlternative object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2PasswordPassword object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + def __eq__( + self, other: 'ProviderPrivateAuthenticationOAuth2PasswordPassword' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: + def __ne__( + self, other: 'ProviderPrivateAuthenticationOAuth2PasswordPassword' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of property observed in "value". + """ + + VALUE = 'value' -class RuntimeEntityInterpretation: + +class ProviderResponse: """ - RuntimeEntityInterpretation. + ProviderResponse. - :param str calendar_type: (optional) The calendar used to represent a recognized - date (for example, `Gregorian`). - :param str datetime_link: (optional) A unique identifier used to associate a - recognized time and date. If the user input contains a date and time that are - mentioned together (for example, `Today at 5`, the same **datetime_link** value - is returned for both the `@sys-date` and `@sys-time` entities). - :param str festival: (optional) A locale-specific holiday name (such as - `thanksgiving` or `christmas`). This property is included when a `@sys-date` - entity is recognized based on a holiday name in the user input. - :param str granularity: (optional) The precision or duration of a time range - specified by a recognized `@sys-time` or `@sys-date` entity. - :param str range_link: (optional) A unique identifier used to associate multiple - recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are - recognized as a range of values in the user's input (for example, `from July 4 - until July 14` or `from 20 to 25`). - :param str range_modifier: (optional) The word in the user input that indicates - that a `sys-date` or `sys-time` entity is part of an implied range where only - one date or time is specified (for example, `since` or `until`). - :param float relative_day: (optional) A recognized mention of a relative day, - represented numerically as an offset from the current date (for example, `-1` - for `yesterday` or `10` for `in ten days`). - :param float relative_month: (optional) A recognized mention of a relative - month, represented numerically as an offset from the current month (for example, - `1` for `next month` or `-3` for `three months ago`). - :param float relative_week: (optional) A recognized mention of a relative week, - represented numerically as an offset from the current week (for example, `2` for - `in two weeks` or `-1` for `last week). - :param float relative_weekend: (optional) A recognized mention of a relative - date range for a weekend, represented numerically as an offset from the current - weekend (for example, `0` for `this weekend` or `-1` for `last weekend`). - :param float relative_year: (optional) A recognized mention of a relative year, - represented numerically as an offset from the current year (for example, `1` for - `next year` or `-5` for `five years ago`). - :param float specific_day: (optional) A recognized mention of a specific date, - represented numerically as the date within the month (for example, `30` for - `June 30`.). - :param str specific_day_of_week: (optional) A recognized mention of a specific - day of the week as a lowercase string (for example, `monday`). - :param float specific_month: (optional) A recognized mention of a specific - month, represented numerically (for example, `7` for `July`). - :param float specific_quarter: (optional) A recognized mention of a specific - quarter, represented numerically (for example, `3` for `the third quarter`). - :param float specific_year: (optional) A recognized mention of a specific year - (for example, `2016`). - :param float numeric_value: (optional) A recognized numeric value, represented - as an integer or double. - :param str subtype: (optional) The type of numeric value recognized in the user - input (`integer` or `rational`). - :param str part_of_day: (optional) A recognized term for a time that was - mentioned as a part of the day in the user's input (for example, `morning` or - `afternoon`). - :param float relative_hour: (optional) A recognized mention of a relative hour, - represented numerically as an offset from the current hour (for example, `3` for - `in three hours` or `-1` for `an hour ago`). - :param float relative_minute: (optional) A recognized mention of a relative - time, represented numerically as an offset in minutes from the current time (for - example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`). - :param float relative_second: (optional) A recognized mention of a relative - time, represented numerically as an offset in seconds from the current time (for - example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). - :param float specific_hour: (optional) A recognized specific hour mentioned as - part of a time value (for example, `10` for `10:15 AM`.). - :param float specific_minute: (optional) A recognized specific minute mentioned - as part of a time value (for example, `15` for `10:15 AM`.). - :param float specific_second: (optional) A recognized specific second mentioned - as part of a time value (for example, `30` for `10:15:30 AM`.). - :param str timezone: (optional) A recognized time zone mentioned as part of a - time value (for example, `EST`). + :param str provider_id: (optional) The unique identifier of the provider. + :param ProviderResponseSpecification specification: (optional) The specification + of the provider. """ def __init__( self, *, - calendar_type: Optional[str] = None, - datetime_link: Optional[str] = None, - festival: Optional[str] = None, - granularity: Optional[str] = None, - range_link: Optional[str] = None, - range_modifier: Optional[str] = None, + provider_id: Optional[str] = None, + specification: Optional['ProviderResponseSpecification'] = None, + ) -> None: + """ + Initialize a ProviderResponse object. + + :param str provider_id: (optional) The unique identifier of the provider. + :param ProviderResponseSpecification specification: (optional) The + specification of the provider. + """ + self.provider_id = provider_id + self.specification = specification + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderResponse': + """Initialize a ProviderResponse object from a json dictionary.""" + args = {} + if (provider_id := _dict.get('provider_id')) is not None: + args['provider_id'] = provider_id + if (specification := _dict.get('specification')) is not None: + args['specification'] = ProviderResponseSpecification.from_dict( + specification) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponse object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'provider_id') and self.provider_id is not None: + _dict['provider_id'] = self.provider_id + if hasattr(self, 'specification') and self.specification is not None: + if isinstance(self.specification, dict): + _dict['specification'] = self.specification + else: + _dict['specification'] = self.specification.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 ProviderResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponse') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecification: + """ + The specification of the provider. + + :param List[ProviderResponseSpecificationServersItem] servers: (optional) An + array of objects defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderResponseSpecificationComponents components: (optional) An object + defining various reusable definitions of the provider. + """ + + def __init__( + self, + *, + servers: Optional[ + List['ProviderResponseSpecificationServersItem']] = None, + components: Optional['ProviderResponseSpecificationComponents'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecification object. + + :param List[ProviderResponseSpecificationServersItem] servers: (optional) + An array of objects defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderResponseSpecificationComponents components: (optional) An + object defining various reusable definitions of the provider. + """ + self.servers = servers + self.components = components + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderResponseSpecification': + """Initialize a ProviderResponseSpecification object from a json dictionary.""" + args = {} + if (servers := _dict.get('servers')) is not None: + args['servers'] = [ + ProviderResponseSpecificationServersItem.from_dict(v) + for v in servers + ] + if (components := _dict.get('components')) is not None: + args[ + 'components'] = ProviderResponseSpecificationComponents.from_dict( + components) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecification object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'servers') and self.servers is not None: + servers_list = [] + for v in self.servers: + if isinstance(v, dict): + servers_list.append(v) + else: + servers_list.append(v.to_dict()) + _dict['servers'] = servers_list + if hasattr(self, 'components') and self.components is not None: + if isinstance(self.components, dict): + _dict['components'] = self.components + else: + _dict['components'] = self.components.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 ProviderResponseSpecification object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponseSpecification') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderResponseSpecification') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecificationComponents: + """ + An object defining various reusable definitions of the provider. + + :param ProviderResponseSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. + """ + + def __init__( + self, + *, + security_schemes: Optional[ + 'ProviderResponseSpecificationComponentsSecuritySchemes'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationComponents object. + + :param ProviderResponseSpecificationComponentsSecuritySchemes + security_schemes: (optional) The definition of the security scheme for the + provider. + """ + self.security_schemes = security_schemes + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'ProviderResponseSpecificationComponents': + """Initialize a ProviderResponseSpecificationComponents object from a json dictionary.""" + args = {} + if (security_schemes := _dict.get('securitySchemes')) is not None: + args[ + 'security_schemes'] = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict( + security_schemes) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationComponents object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'security_schemes') and self.security_schemes is not None: + if isinstance(self.security_schemes, dict): + _dict['securitySchemes'] = self.security_schemes + else: + _dict['securitySchemes'] = self.security_schemes.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 ProviderResponseSpecificationComponents object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponseSpecificationComponents') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderResponseSpecificationComponents') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecificationComponentsSecuritySchemes: + """ + The definition of the security scheme for the provider. + + :param str authentication_method: (optional) The authentication method required + for requests made from watsonx Assistant to the conversational skill provider. + :param ProviderResponseSpecificationComponentsSecuritySchemesBasic basic: + (optional) Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings for + oauth2 authentication. + """ + + def __init__( + self, + *, + authentication_method: Optional[str] = None, + basic: Optional[ + 'ProviderResponseSpecificationComponentsSecuritySchemesBasic'] = None, + oauth2: Optional['ProviderAuthenticationOAuth2'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object. + + :param str authentication_method: (optional) The authentication method + required for requests made from watsonx Assistant to the conversational + skill provider. + :param ProviderResponseSpecificationComponentsSecuritySchemesBasic basic: + (optional) Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings + for oauth2 authentication. + """ + self.authentication_method = authentication_method + self.basic = basic + self.oauth2 = oauth2 + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'ProviderResponseSpecificationComponentsSecuritySchemes': + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object from a json dictionary.""" + args = {} + if (authentication_method := + _dict.get('authentication_method')) is not None: + args['authentication_method'] = authentication_method + if (basic := _dict.get('basic')) is not None: + args[ + 'basic'] = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict( + basic) + if (oauth2 := _dict.get('oauth2')) is not None: + args['oauth2'] = ProviderAuthenticationOAuth2.from_dict(oauth2) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'authentication_method' + ) and self.authentication_method is not None: + _dict['authentication_method'] = self.authentication_method + if hasattr(self, 'basic') and self.basic is not None: + if isinstance(self.basic, dict): + _dict['basic'] = self.basic + else: + _dict['basic'] = self.basic.to_dict() + if hasattr(self, 'oauth2') and self.oauth2 is not None: + if isinstance(self.oauth2, dict): + _dict['oauth2'] = self.oauth2 + else: + _dict['oauth2'] = self.oauth2.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 ProviderResponseSpecificationComponentsSecuritySchemes object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'ProviderResponseSpecificationComponentsSecuritySchemes' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, other: 'ProviderResponseSpecificationComponentsSecuritySchemes' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class AuthenticationMethodEnum(str, Enum): + """ + The authentication method required for requests made from watsonx Assistant to the + conversational skill provider. + """ + + BASIC = 'basic' + BEARER = 'bearer' + API_KEY = 'api_key' + OAUTH2 = 'oauth2' + NONE = 'none' + + +class ProviderResponseSpecificationComponentsSecuritySchemesBasic: + """ + Non-private settings for basic access authentication. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username for + basic access authentication. + """ + + def __init__( + self, + *, + username: Optional['ProviderAuthenticationTypeAndValue'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username + for basic access authentication. + """ + self.username = username + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'ProviderResponseSpecificationComponentsSecuritySchemesBasic': + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + args = {} + if (username := _dict.get('username')) is not None: + args['username'] = ProviderAuthenticationTypeAndValue.from_dict( + username) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'username') and self.username is not None: + if isinstance(self.username, dict): + _dict['username'] = self.username + else: + _dict['username'] = self.username.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 ProviderResponseSpecificationComponentsSecuritySchemesBasic object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'ProviderResponseSpecificationComponentsSecuritySchemesBasic' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, + other: 'ProviderResponseSpecificationComponentsSecuritySchemesBasic' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecificationServersItem: + """ + ProviderResponseSpecificationServersItem. + + :param str url: (optional) The URL of the conversational skill provider. + """ + + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationServersItem object. + + :param str url: (optional) The URL of the conversational skill provider. + """ + self.url = url + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'ProviderResponseSpecificationServersItem': + """Initialize a ProviderResponseSpecificationServersItem object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationServersItem object from 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: + _dict['url'] = self.url + 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 ProviderResponseSpecificationServersItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponseSpecificationServersItem') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderResponseSpecificationServersItem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecification: + """ + The specification of the provider. + + :param List[ProviderSpecificationServersItem] servers: An array of objects + defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderSpecificationComponents components: (optional) An object defining + various reusable definitions of the provider. + """ + + def __init__( + self, + servers: List['ProviderSpecificationServersItem'], + *, + components: Optional['ProviderSpecificationComponents'] = None, + ) -> None: + """ + Initialize a ProviderSpecification object. + + :param List[ProviderSpecificationServersItem] servers: An array of objects + defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderSpecificationComponents components: (optional) An object + defining various reusable definitions of the provider. + """ + self.servers = servers + self.components = components + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderSpecification': + """Initialize a ProviderSpecification object from a json dictionary.""" + args = {} + if (servers := _dict.get('servers')) is not None: + args['servers'] = [ + ProviderSpecificationServersItem.from_dict(v) for v in servers + ] + else: + raise ValueError( + 'Required property \'servers\' not present in ProviderSpecification JSON' + ) + if (components := _dict.get('components')) is not None: + args['components'] = ProviderSpecificationComponents.from_dict( + components) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecification object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'servers') and self.servers is not None: + servers_list = [] + for v in self.servers: + if isinstance(v, dict): + servers_list.append(v) + else: + servers_list.append(v.to_dict()) + _dict['servers'] = servers_list + if hasattr(self, 'components') and self.components is not None: + if isinstance(self.components, dict): + _dict['components'] = self.components + else: + _dict['components'] = self.components.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 ProviderSpecification object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderSpecification') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderSpecification') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecificationComponents: + """ + An object defining various reusable definitions of the provider. + + :param ProviderSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. + """ + + def __init__( + self, + *, + security_schemes: Optional[ + 'ProviderSpecificationComponentsSecuritySchemes'] = None, + ) -> None: + """ + Initialize a ProviderSpecificationComponents object. + + :param ProviderSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. + """ + self.security_schemes = security_schemes + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderSpecificationComponents': + """Initialize a ProviderSpecificationComponents object from a json dictionary.""" + args = {} + if (security_schemes := _dict.get('securitySchemes')) is not None: + args[ + 'security_schemes'] = ProviderSpecificationComponentsSecuritySchemes.from_dict( + security_schemes) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationComponents object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'security_schemes') and self.security_schemes is not None: + if isinstance(self.security_schemes, dict): + _dict['securitySchemes'] = self.security_schemes + else: + _dict['securitySchemes'] = self.security_schemes.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 ProviderSpecificationComponents object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderSpecificationComponents') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderSpecificationComponents') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecificationComponentsSecuritySchemes: + """ + The definition of the security scheme for the provider. + + :param str authentication_method: (optional) The authentication method required + for requests made from watsonx Assistant to the conversational skill provider. + :param ProviderSpecificationComponentsSecuritySchemesBasic basic: (optional) + Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings for + oauth2 authentication. + """ + + def __init__( + self, + *, + authentication_method: Optional[str] = None, + basic: Optional[ + 'ProviderSpecificationComponentsSecuritySchemesBasic'] = None, + oauth2: Optional['ProviderAuthenticationOAuth2'] = None, + ) -> None: + """ + Initialize a ProviderSpecificationComponentsSecuritySchemes object. + + :param str authentication_method: (optional) The authentication method + required for requests made from watsonx Assistant to the conversational + skill provider. + :param ProviderSpecificationComponentsSecuritySchemesBasic basic: + (optional) Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings + for oauth2 authentication. + """ + self.authentication_method = authentication_method + self.basic = basic + self.oauth2 = oauth2 + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'ProviderSpecificationComponentsSecuritySchemes': + """Initialize a ProviderSpecificationComponentsSecuritySchemes object from a json dictionary.""" + args = {} + if (authentication_method := + _dict.get('authentication_method')) is not None: + args['authentication_method'] = authentication_method + if (basic := _dict.get('basic')) is not None: + args[ + 'basic'] = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict( + basic) + if (oauth2 := _dict.get('oauth2')) is not None: + args['oauth2'] = ProviderAuthenticationOAuth2.from_dict(oauth2) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationComponentsSecuritySchemes object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'authentication_method' + ) and self.authentication_method is not None: + _dict['authentication_method'] = self.authentication_method + if hasattr(self, 'basic') and self.basic is not None: + if isinstance(self.basic, dict): + _dict['basic'] = self.basic + else: + _dict['basic'] = self.basic.to_dict() + if hasattr(self, 'oauth2') and self.oauth2 is not None: + if isinstance(self.oauth2, dict): + _dict['oauth2'] = self.oauth2 + else: + _dict['oauth2'] = self.oauth2.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 ProviderSpecificationComponentsSecuritySchemes object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'ProviderSpecificationComponentsSecuritySchemes') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, + other: 'ProviderSpecificationComponentsSecuritySchemes') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class AuthenticationMethodEnum(str, Enum): + """ + The authentication method required for requests made from watsonx Assistant to the + conversational skill provider. + """ + + BASIC = 'basic' + BEARER = 'bearer' + API_KEY = 'api_key' + OAUTH2 = 'oauth2' + NONE = 'none' + + +class ProviderSpecificationComponentsSecuritySchemesBasic: + """ + Non-private settings for basic access authentication. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username for + basic access authentication. + """ + + def __init__( + self, + *, + username: Optional['ProviderAuthenticationTypeAndValue'] = None, + ) -> None: + """ + Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username + for basic access authentication. + """ + self.username = username + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'ProviderSpecificationComponentsSecuritySchemesBasic': + """Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + args = {} + if (username := _dict.get('username')) is not None: + args['username'] = ProviderAuthenticationTypeAndValue.from_dict( + username) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'username') and self.username is not None: + if isinstance(self.username, dict): + _dict['username'] = self.username + else: + _dict['username'] = self.username.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 ProviderSpecificationComponentsSecuritySchemesBasic object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'ProviderSpecificationComponentsSecuritySchemesBasic' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, other: 'ProviderSpecificationComponentsSecuritySchemesBasic' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecificationServersItem: + """ + ProviderSpecificationServersItem. + + :param str url: (optional) The URL of the conversational skill provider. + """ + + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: + """ + Initialize a ProviderSpecificationServersItem object. + + :param str url: (optional) The URL of the conversational skill provider. + """ + self.url = url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderSpecificationServersItem': + """Initialize a ProviderSpecificationServersItem object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationServersItem object from 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: + _dict['url'] = self.url + 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 ProviderSpecificationServersItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderSpecificationServersItem') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ProviderSpecificationServersItem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Release: + """ + Release. + + :param str release: (optional) The name of the release. The name is the version + number (an integer), returned as a string. + :param str description: (optional) The description of the release. + :param List[EnvironmentReference] environment_references: (optional) An array of + objects describing the environments where this release has been deployed. + :param ReleaseContent content: (optional) An object identifying the versionable + content objects (such as skill snapshots) that are included in the release. + :param str status: (optional) The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. + """ + + def __init__( + self, + *, + release: Optional[str] = None, + description: Optional[str] = None, + environment_references: Optional[List['EnvironmentReference']] = None, + content: Optional['ReleaseContent'] = None, + status: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: + """ + Initialize a Release object. + + :param str description: (optional) The description of the release. + """ + self.release = release + self.description = description + self.environment_references = environment_references + self.content = content + self.status = status + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Release': + """Initialize a Release object from a json dictionary.""" + args = {} + if (release := _dict.get('release')) is not None: + args['release'] = release + if (description := _dict.get('description')) is not None: + args['description'] = description + if (environment_references := + _dict.get('environment_references')) is not None: + args['environment_references'] = [ + EnvironmentReference.from_dict(v) + for v in environment_references + ] + if (content := _dict.get('content')) is not None: + args['content'] = ReleaseContent.from_dict(content) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Release object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'release') and getattr(self, 'release') is not None: + _dict['release'] = getattr(self, 'release') + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'environment_references') and getattr( + self, 'environment_references') is not None: + environment_references_list = [] + for v in getattr(self, 'environment_references'): + if isinstance(v, dict): + environment_references_list.append(v) + else: + environment_references_list.append(v.to_dict()) + _dict['environment_references'] = environment_references_list + if hasattr(self, 'content') and getattr(self, 'content') is not None: + if isinstance(getattr(self, 'content'), dict): + _dict['content'] = getattr(self, 'content') + else: + _dict['content'] = getattr(self, 'content').to_dict() + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + 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 Release object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Release') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'Release') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class ReleaseCollection: + """ + ReleaseCollection. + + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). + """ + + def __init__( + self, + releases: List['Release'], + pagination: 'Pagination', + ) -> None: + """ + Initialize a ReleaseCollection object. + + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + self.releases = releases + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': + """Initialize a ReleaseCollection object from a json dictionary.""" + args = {} + if (releases := _dict.get('releases')) is not None: + args['releases'] = [Release.from_dict(v) for v in releases] + else: + raise ValueError( + 'Required property \'releases\' not present in ReleaseCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in ReleaseCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseCollection object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'releases') and self.releases is not None: + releases_list = [] + for v in self.releases: + if isinstance(v, dict): + releases_list.append(v) + else: + releases_list.append(v.to_dict()) + _dict['releases'] = releases_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.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 ReleaseCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseCollection') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ReleaseCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseContent: + """ + An object identifying the versionable content objects (such as skill snapshots) that + are included in the release. + + :param List[ReleaseSkill] skills: (optional) The skill snapshots that are + included in the release. + """ + + def __init__( + self, + *, + skills: Optional[List['ReleaseSkill']] = None, + ) -> None: + """ + Initialize a ReleaseContent object. + + """ + self.skills = skills + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseContent': + """Initialize a ReleaseContent object from a json dictionary.""" + args = {} + if (skills := _dict.get('skills')) is not None: + args['skills'] = [ReleaseSkill.from_dict(v) for v in skills] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseContent object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'skills') and getattr(self, 'skills') is not None: + skills_list = [] + for v in getattr(self, 'skills'): + if isinstance(v, dict): + skills_list.append(v) + else: + skills_list.append(v.to_dict()) + _dict['skills'] = skills_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this ReleaseContent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseContent') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ReleaseContent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseSkill: + """ + ReleaseSkill. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is saved as + part of the release (for example, `draft` or `1`). + """ + + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + snapshot: Optional[str] = None, + ) -> None: + """ + Initialize a ReleaseSkill object. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is + saved as part of the release (for example, `draft` or `1`). + """ + self.skill_id = skill_id + self.type = type + self.snapshot = snapshot + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': + """Initialize a ReleaseSkill object from a json dictionary.""" + args = {} + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + else: + raise ValueError( + 'Required property \'skill_id\' not present in ReleaseSkill JSON' + ) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseSkill object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + 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 ReleaseSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseSkill') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ReleaseSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of the skill. + """ + + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + + +class RequestAnalytics: + """ + An optional object containing analytics data. Currently, this data is used only for + events sent to the Segment extension. + + :param str browser: (optional) The browser that was used to send the message + that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to send + the message that triggered the event. + """ + + def __init__( + self, + *, + browser: Optional[str] = None, + device: Optional[str] = None, + page_url: Optional[str] = None, + ) -> None: + """ + Initialize a RequestAnalytics object. + + :param str browser: (optional) The browser that was used to send the + message that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to + send the message that triggered the event. + """ + self.browser = browser + self.device = device + self.page_url = page_url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': + """Initialize a RequestAnalytics object from a json dictionary.""" + args = {} + if (browser := _dict.get('browser')) is not None: + args['browser'] = browser + if (device := _dict.get('device')) is not None: + args['device'] = device + if (page_url := _dict.get('pageUrl')) is not None: + args['page_url'] = page_url + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RequestAnalytics object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'browser') and self.browser is not None: + _dict['browser'] = self.browser + if hasattr(self, 'device') and self.device is not None: + _dict['device'] = self.device + if hasattr(self, 'page_url') and self.page_url is not None: + _dict['pageUrl'] = self.page_url + 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 RequestAnalytics object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RequestAnalytics') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RequestAnalytics') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericChannel: + """ + ResponseGenericChannel. + + :param str channel: (optional) A channel for which the response is intended. + """ + + def __init__( + self, + *, + channel: Optional[str] = None, + ) -> None: + """ + Initialize a ResponseGenericChannel object. + + :param str channel: (optional) A channel for which the response is + intended. + """ + self.channel = channel + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': + """Initialize a ResponseGenericChannel object from a json dictionary.""" + args = {} + if (channel := _dict.get('channel')) is not None: + args['channel'] = channel + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericChannel object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'channel') and self.channel is not None: + _dict['channel'] = self.channel + 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 ResponseGenericChannel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntity: + """ + The entity value that was recognized in the user input. + + :param str entity: An entity detected in the input. + :param List[int] location: (optional) An array of zero-based character offsets + that indicate where the detected entity values begin and end in the input text. + :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 + confidence in the recognized entity. + :param List[CaptureGroup] groups: (optional) The recognized capture groups for + the entity, as defined by the entity pattern. + :param RuntimeEntityInterpretation interpretation: (optional) An object + containing detailed information about the entity recognized in the user input. + This property is included only if the new system entities are enabled for the + skill. + For more information about how the new system entities are interpreted, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). + :param List[RuntimeEntityAlternative] alternatives: (optional) An array of + possible alternative values that the user might have intended instead of the + value returned in the **value** property. This property is returned only for + `@sys-time` and `@sys-date` entities when the user's input is ambiguous. + This property is included only if the new system entities are enabled for the + skill. + :param RuntimeEntityRole role: (optional) An object describing the role played + by a system entity that is specifies the beginning or end of a range recognized + in the user input. This property is included only if the new system entities are + enabled for the skill. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill (if + enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__( + self, + entity: str, + value: str, + *, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + groups: Optional[List['CaptureGroup']] = None, + interpretation: Optional['RuntimeEntityInterpretation'] = None, + alternatives: Optional[List['RuntimeEntityAlternative']] = None, + role: Optional['RuntimeEntityRole'] = None, + skill: Optional[str] = None, + ) -> None: + """ + Initialize a RuntimeEntity object. + + :param str entity: An entity detected in the input. + :param str value: The term in the input text that was recognized as an + entity value. + :param List[int] location: (optional) An array of zero-based character + offsets that indicate where the detected entity values begin and end in the + input text. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized entity. + :param List[CaptureGroup] groups: (optional) The recognized capture groups + for the entity, as defined by the entity pattern. + :param RuntimeEntityInterpretation interpretation: (optional) An object + containing detailed information about the entity recognized in the user + input. This property is included only if the new system entities are + enabled for the skill. + For more information about how the new system entities are interpreted, see + the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-beta-system-entities). + :param List[RuntimeEntityAlternative] alternatives: (optional) An array of + possible alternative values that the user might have intended instead of + the value returned in the **value** property. This property is returned + only for `@sys-time` and `@sys-date` entities when the user's input is + ambiguous. + This property is included only if the new system entities are enabled for + the skill. + :param RuntimeEntityRole role: (optional) An object describing the role + played by a system entity that is specifies the beginning or end of a range + recognized in the user input. This property is included only if the new + system entities are enabled for the skill. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.entity = entity + self.location = location + self.value = value + self.confidence = confidence + self.groups = groups + self.interpretation = interpretation + self.alternatives = alternatives + self.role = role + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': + """Initialize a RuntimeEntity object from a json dictionary.""" + args = {} + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity + else: + raise ValueError( + 'Required property \'entity\' not present in RuntimeEntity JSON' + ) + if (location := _dict.get('location')) is not None: + args['location'] = location + if (value := _dict.get('value')) is not None: + args['value'] = value + else: + raise ValueError( + 'Required property \'value\' not present in RuntimeEntity JSON') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (groups := _dict.get('groups')) is not None: + args['groups'] = [CaptureGroup.from_dict(v) for v in groups] + if (interpretation := _dict.get('interpretation')) is not None: + args['interpretation'] = RuntimeEntityInterpretation.from_dict( + interpretation) + if (alternatives := _dict.get('alternatives')) is not None: + args['alternatives'] = [ + RuntimeEntityAlternative.from_dict(v) for v in alternatives + ] + if (role := _dict.get('role')) is not None: + args['role'] = RuntimeEntityRole.from_dict(role) + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill + return cls(**args) + + @classmethod + 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: + _dict['entity'] = self.entity + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'groups') and self.groups is not None: + groups_list = [] + for v in self.groups: + if isinstance(v, dict): + groups_list.append(v) + else: + groups_list.append(v.to_dict()) + _dict['groups'] = groups_list + if hasattr(self, 'interpretation') and self.interpretation is not None: + if isinstance(self.interpretation, dict): + _dict['interpretation'] = self.interpretation + else: + _dict['interpretation'] = self.interpretation.to_dict() + if hasattr(self, 'alternatives') and self.alternatives is not None: + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list + if hasattr(self, 'role') and self.role is not None: + if isinstance(self.role, dict): + _dict['role'] = self.role + else: + _dict['role'] = self.role.to_dict() + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + 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 RuntimeEntity object.""" + return json.dumps(self.to_dict(), indent=2) + + 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: 'RuntimeEntity') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntityAlternative: + """ + An alternative value for the recognized entity. + + :param str value: (optional) The entity value that was recognized in the user + input. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized entity. + """ + + def __init__( + self, + *, + value: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: + """ + Initialize a RuntimeEntityAlternative object. + + :param str value: (optional) The entity value that was recognized in the + user input. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized entity. + """ + self.value = value + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': + """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + args = {} + if (value := _dict.get('value')) is not None: + args['value'] = value + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityAlternative object from 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: + _dict['value'] = self.value + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + 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 RuntimeEntityAlternative object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntityInterpretation: + """ + RuntimeEntityInterpretation. + + :param str calendar_type: (optional) The calendar used to represent a recognized + date (for example, `Gregorian`). + :param str datetime_link: (optional) A unique identifier used to associate a + recognized time and date. If the user input contains a date and time that are + mentioned together (for example, `Today at 5`, the same **datetime_link** value + is returned for both the `@sys-date` and `@sys-time` entities). + :param str festival: (optional) A locale-specific holiday name (such as + `thanksgiving` or `christmas`). This property is included when a `@sys-date` + entity is recognized based on a holiday name in the user input. + :param str granularity: (optional) The precision or duration of a time range + specified by a recognized `@sys-time` or `@sys-date` entity. + :param str range_link: (optional) A unique identifier used to associate multiple + recognized `@sys-date`, `@sys-time`, or `@sys-number` entities that are + recognized as a range of values in the user's input (for example, `from July 4 + until July 14` or `from 20 to 25`). + :param str range_modifier: (optional) The word in the user input that indicates + that a `sys-date` or `sys-time` entity is part of an implied range where only + one date or time is specified (for example, `since` or `until`). + :param float relative_day: (optional) A recognized mention of a relative day, + represented numerically as an offset from the current date (for example, `-1` + for `yesterday` or `10` for `in ten days`). + :param float relative_month: (optional) A recognized mention of a relative + month, represented numerically as an offset from the current month (for example, + `1` for `next month` or `-3` for `three months ago`). + :param float relative_week: (optional) A recognized mention of a relative week, + represented numerically as an offset from the current week (for example, `2` for + `in two weeks` or `-1` for `last week). + :param float relative_weekend: (optional) A recognized mention of a relative + date range for a weekend, represented numerically as an offset from the current + weekend (for example, `0` for `this weekend` or `-1` for `last weekend`). + :param float relative_year: (optional) A recognized mention of a relative year, + represented numerically as an offset from the current year (for example, `1` for + `next year` or `-5` for `five years ago`). + :param float specific_day: (optional) A recognized mention of a specific date, + represented numerically as the date within the month (for example, `30` for + `June 30`.). + :param str specific_day_of_week: (optional) A recognized mention of a specific + day of the week as a lowercase string (for example, `monday`). + :param float specific_month: (optional) A recognized mention of a specific + month, represented numerically (for example, `7` for `July`). + :param float specific_quarter: (optional) A recognized mention of a specific + quarter, represented numerically (for example, `3` for `the third quarter`). + :param float specific_year: (optional) A recognized mention of a specific year + (for example, `2016`). + :param float numeric_value: (optional) A recognized numeric value, represented + as an integer or double. + :param str subtype: (optional) The type of numeric value recognized in the user + input (`integer` or `rational`). + :param str part_of_day: (optional) A recognized term for a time that was + mentioned as a part of the day in the user's input (for example, `morning` or + `afternoon`). + :param float relative_hour: (optional) A recognized mention of a relative hour, + represented numerically as an offset from the current hour (for example, `3` for + `in three hours` or `-1` for `an hour ago`). + :param float relative_minute: (optional) A recognized mention of a relative + time, represented numerically as an offset in minutes from the current time (for + example, `5` for `in five minutes` or `-15` for `fifteen minutes ago`). + :param float relative_second: (optional) A recognized mention of a relative + time, represented numerically as an offset in seconds from the current time (for + example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). + :param float specific_hour: (optional) A recognized specific hour mentioned as + part of a time value (for example, `10` for `10:15 AM`.). + :param float specific_minute: (optional) A recognized specific minute mentioned + as part of a time value (for example, `15` for `10:15 AM`.). + :param float specific_second: (optional) A recognized specific second mentioned + as part of a time value (for example, `30` for `10:15:30 AM`.). + :param str timezone: (optional) A recognized time zone mentioned as part of a + time value (for example, `EST`). + """ + + def __init__( + self, + *, + calendar_type: Optional[str] = None, + datetime_link: Optional[str] = None, + festival: Optional[str] = None, + granularity: Optional[str] = None, + range_link: Optional[str] = None, + range_modifier: Optional[str] = None, relative_day: Optional[float] = None, relative_month: Optional[float] = None, relative_week: Optional[float] = None, @@ -7913,235 +10611,2611 @@ def __init__( timezone: Optional[str] = None, ) -> None: """ - Initialize a RuntimeEntityInterpretation object. + Initialize a RuntimeEntityInterpretation object. + + :param str calendar_type: (optional) The calendar used to represent a + recognized date (for example, `Gregorian`). + :param str datetime_link: (optional) A unique identifier used to associate + a recognized time and date. If the user input contains a date and time that + are mentioned together (for example, `Today at 5`, the same + **datetime_link** value is returned for both the `@sys-date` and + `@sys-time` entities). + :param str festival: (optional) A locale-specific holiday name (such as + `thanksgiving` or `christmas`). This property is included when a + `@sys-date` entity is recognized based on a holiday name in the user input. + :param str granularity: (optional) The precision or duration of a time + range specified by a recognized `@sys-time` or `@sys-date` entity. + :param str range_link: (optional) A unique identifier used to associate + multiple recognized `@sys-date`, `@sys-time`, or `@sys-number` entities + that are recognized as a range of values in the user's input (for example, + `from July 4 until July 14` or `from 20 to 25`). + :param str range_modifier: (optional) The word in the user input that + indicates that a `sys-date` or `sys-time` entity is part of an implied + range where only one date or time is specified (for example, `since` or + `until`). + :param float relative_day: (optional) A recognized mention of a relative + day, represented numerically as an offset from the current date (for + example, `-1` for `yesterday` or `10` for `in ten days`). + :param float relative_month: (optional) A recognized mention of a relative + month, represented numerically as an offset from the current month (for + example, `1` for `next month` or `-3` for `three months ago`). + :param float relative_week: (optional) A recognized mention of a relative + week, represented numerically as an offset from the current week (for + example, `2` for `in two weeks` or `-1` for `last week). + :param float relative_weekend: (optional) A recognized mention of a + relative date range for a weekend, represented numerically as an offset + from the current weekend (for example, `0` for `this weekend` or `-1` for + `last weekend`). + :param float relative_year: (optional) A recognized mention of a relative + year, represented numerically as an offset from the current year (for + example, `1` for `next year` or `-5` for `five years ago`). + :param float specific_day: (optional) A recognized mention of a specific + date, represented numerically as the date within the month (for example, + `30` for `June 30`.). + :param str specific_day_of_week: (optional) A recognized mention of a + specific day of the week as a lowercase string (for example, `monday`). + :param float specific_month: (optional) A recognized mention of a specific + month, represented numerically (for example, `7` for `July`). + :param float specific_quarter: (optional) A recognized mention of a + specific quarter, represented numerically (for example, `3` for `the third + quarter`). + :param float specific_year: (optional) A recognized mention of a specific + year (for example, `2016`). + :param float numeric_value: (optional) A recognized numeric value, + represented as an integer or double. + :param str subtype: (optional) The type of numeric value recognized in the + user input (`integer` or `rational`). + :param str part_of_day: (optional) A recognized term for a time that was + mentioned as a part of the day in the user's input (for example, `morning` + or `afternoon`). + :param float relative_hour: (optional) A recognized mention of a relative + hour, represented numerically as an offset from the current hour (for + example, `3` for `in three hours` or `-1` for `an hour ago`). + :param float relative_minute: (optional) A recognized mention of a relative + time, represented numerically as an offset in minutes from the current time + (for example, `5` for `in five minutes` or `-15` for `fifteen minutes + ago`). + :param float relative_second: (optional) A recognized mention of a relative + time, represented numerically as an offset in seconds from the current time + (for example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). + :param float specific_hour: (optional) A recognized specific hour mentioned + as part of a time value (for example, `10` for `10:15 AM`.). + :param float specific_minute: (optional) A recognized specific minute + mentioned as part of a time value (for example, `15` for `10:15 AM`.). + :param float specific_second: (optional) A recognized specific second + mentioned as part of a time value (for example, `30` for `10:15:30 AM`.). + :param str timezone: (optional) A recognized time zone mentioned as part of + a time value (for example, `EST`). + """ + self.calendar_type = calendar_type + self.datetime_link = datetime_link + self.festival = festival + self.granularity = granularity + self.range_link = range_link + self.range_modifier = range_modifier + self.relative_day = relative_day + self.relative_month = relative_month + self.relative_week = relative_week + self.relative_weekend = relative_weekend + self.relative_year = relative_year + self.specific_day = specific_day + self.specific_day_of_week = specific_day_of_week + self.specific_month = specific_month + self.specific_quarter = specific_quarter + self.specific_year = specific_year + self.numeric_value = numeric_value + self.subtype = subtype + self.part_of_day = part_of_day + self.relative_hour = relative_hour + self.relative_minute = relative_minute + self.relative_second = relative_second + self.specific_hour = specific_hour + self.specific_minute = specific_minute + self.specific_second = specific_second + self.timezone = timezone + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': + """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + args = {} + if (calendar_type := _dict.get('calendar_type')) is not None: + args['calendar_type'] = calendar_type + if (datetime_link := _dict.get('datetime_link')) is not None: + args['datetime_link'] = datetime_link + if (festival := _dict.get('festival')) is not None: + args['festival'] = festival + if (granularity := _dict.get('granularity')) is not None: + args['granularity'] = granularity + if (range_link := _dict.get('range_link')) is not None: + args['range_link'] = range_link + if (range_modifier := _dict.get('range_modifier')) is not None: + args['range_modifier'] = range_modifier + if (relative_day := _dict.get('relative_day')) is not None: + args['relative_day'] = relative_day + if (relative_month := _dict.get('relative_month')) is not None: + args['relative_month'] = relative_month + if (relative_week := _dict.get('relative_week')) is not None: + args['relative_week'] = relative_week + if (relative_weekend := _dict.get('relative_weekend')) is not None: + args['relative_weekend'] = relative_weekend + if (relative_year := _dict.get('relative_year')) is not None: + args['relative_year'] = relative_year + if (specific_day := _dict.get('specific_day')) is not None: + args['specific_day'] = specific_day + if (specific_day_of_week := + _dict.get('specific_day_of_week')) is not None: + args['specific_day_of_week'] = specific_day_of_week + if (specific_month := _dict.get('specific_month')) is not None: + args['specific_month'] = specific_month + if (specific_quarter := _dict.get('specific_quarter')) is not None: + args['specific_quarter'] = specific_quarter + if (specific_year := _dict.get('specific_year')) is not None: + args['specific_year'] = specific_year + if (numeric_value := _dict.get('numeric_value')) is not None: + args['numeric_value'] = numeric_value + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype + if (part_of_day := _dict.get('part_of_day')) is not None: + args['part_of_day'] = part_of_day + if (relative_hour := _dict.get('relative_hour')) is not None: + args['relative_hour'] = relative_hour + if (relative_minute := _dict.get('relative_minute')) is not None: + args['relative_minute'] = relative_minute + if (relative_second := _dict.get('relative_second')) is not None: + args['relative_second'] = relative_second + if (specific_hour := _dict.get('specific_hour')) is not None: + args['specific_hour'] = specific_hour + if (specific_minute := _dict.get('specific_minute')) is not None: + args['specific_minute'] = specific_minute + if (specific_second := _dict.get('specific_second')) is not None: + args['specific_second'] = specific_second + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'calendar_type') and self.calendar_type is not None: + _dict['calendar_type'] = self.calendar_type + if hasattr(self, 'datetime_link') and self.datetime_link is not None: + _dict['datetime_link'] = self.datetime_link + if hasattr(self, 'festival') and self.festival is not None: + _dict['festival'] = self.festival + if hasattr(self, 'granularity') and self.granularity is not None: + _dict['granularity'] = self.granularity + if hasattr(self, 'range_link') and self.range_link is not None: + _dict['range_link'] = self.range_link + if hasattr(self, 'range_modifier') and self.range_modifier is not None: + _dict['range_modifier'] = self.range_modifier + if hasattr(self, 'relative_day') and self.relative_day is not None: + _dict['relative_day'] = self.relative_day + if hasattr(self, 'relative_month') and self.relative_month is not None: + _dict['relative_month'] = self.relative_month + if hasattr(self, 'relative_week') and self.relative_week is not None: + _dict['relative_week'] = self.relative_week + if hasattr(self, + 'relative_weekend') and self.relative_weekend is not None: + _dict['relative_weekend'] = self.relative_weekend + if hasattr(self, 'relative_year') and self.relative_year is not None: + _dict['relative_year'] = self.relative_year + if hasattr(self, 'specific_day') and self.specific_day is not None: + _dict['specific_day'] = self.specific_day + if hasattr(self, 'specific_day_of_week' + ) and self.specific_day_of_week is not None: + _dict['specific_day_of_week'] = self.specific_day_of_week + if hasattr(self, 'specific_month') and self.specific_month is not None: + _dict['specific_month'] = self.specific_month + if hasattr(self, + 'specific_quarter') and self.specific_quarter is not None: + _dict['specific_quarter'] = self.specific_quarter + if hasattr(self, 'specific_year') and self.specific_year is not None: + _dict['specific_year'] = self.specific_year + if hasattr(self, 'numeric_value') and self.numeric_value is not None: + _dict['numeric_value'] = self.numeric_value + if hasattr(self, 'subtype') and self.subtype is not None: + _dict['subtype'] = self.subtype + if hasattr(self, 'part_of_day') and self.part_of_day is not None: + _dict['part_of_day'] = self.part_of_day + if hasattr(self, 'relative_hour') and self.relative_hour is not None: + _dict['relative_hour'] = self.relative_hour + if hasattr(self, + 'relative_minute') and self.relative_minute is not None: + _dict['relative_minute'] = self.relative_minute + if hasattr(self, + 'relative_second') and self.relative_second is not None: + _dict['relative_second'] = self.relative_second + if hasattr(self, 'specific_hour') and self.specific_hour is not None: + _dict['specific_hour'] = self.specific_hour + if hasattr(self, + 'specific_minute') and self.specific_minute is not None: + _dict['specific_minute'] = self.specific_minute + if hasattr(self, + 'specific_second') and self.specific_second is not None: + _dict['specific_second'] = self.specific_second + if hasattr(self, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + 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 RuntimeEntityInterpretation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityInterpretation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class GranularityEnum(str, Enum): + """ + The precision or duration of a time range specified by a recognized `@sys-time` or + `@sys-date` entity. + """ + + DAY = 'day' + FORTNIGHT = 'fortnight' + HOUR = 'hour' + INSTANT = 'instant' + MINUTE = 'minute' + MONTH = 'month' + QUARTER = 'quarter' + SECOND = 'second' + WEEK = 'week' + WEEKEND = 'weekend' + YEAR = 'year' + + +class RuntimeEntityRole: + """ + An object describing the role played by a system entity that is specifies the + beginning or end of a range recognized in the user input. This property is included + only if the new system entities are enabled for the skill. + + :param str type: (optional) The relationship of the entity to the range. + """ + + def __init__( + self, + *, + type: Optional[str] = None, + ) -> None: + """ + Initialize a RuntimeEntityRole object. + + :param str type: (optional) The relationship of the entity to the range. + """ + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': + """Initialize a RuntimeEntityRole object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntityRole object from 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 _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this RuntimeEntityRole object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntityRole') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'RuntimeEntityRole') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The relationship of the entity to the range. + """ + + DATE_FROM = 'date_from' + DATE_TO = 'date_to' + NUMBER_FROM = 'number_from' + NUMBER_TO = 'number_to' + TIME_FROM = 'time_from' + TIME_TO = 'time_to' + + +class RuntimeIntent: + """ + An intent identified in the user input. + + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. + :param str skill: (optional) The skill that identified the intent. Currently, + the only possible values are `main skill` for the dialog skill (if enabled) and + `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__( + self, + intent: str, + *, + confidence: Optional[float] = None, + skill: Optional[str] = None, + ) -> None: + """ + Initialize a RuntimeIntent object. + + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. + :param str skill: (optional) The skill that identified the intent. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.intent = intent + self.confidence = confidence + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': + """Initialize a RuntimeIntent object from a json dictionary.""" + args = {} + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent + else: + raise ValueError( + 'Required property \'intent\' not present in RuntimeIntent JSON' + ) + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill + return cls(**args) + + @classmethod + 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: + _dict['intent'] = self.intent + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + 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 RuntimeIntent object.""" + return json.dumps(self.to_dict(), indent=2) + + 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: 'RuntimeIntent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGeneric: + """ + RuntimeResponseGeneric. + + """ + + def __init__(self,) -> None: + """ + Initialize a RuntimeResponseGeneric object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' + mapping[ + 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + mapping[ + 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' + mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' + mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' + mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' + mapping[ + 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' + mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' + mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + mapping[ + 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric 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 SearchResult: + """ + SearchResult. + + :param str id: The unique identifier of the document in the Discovery service + collection. + This property is included in responses from search skills, which are available + only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search result + metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is taken + from an abstract, summary, or highlight field in the Discovery service response, + as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken from + a title or name field in the Discovery service response, as specified in the + search skill configuration. + :param str url: (optional) The URL of the original data object in its native + data source. + :param SearchResultHighlight highlight: (optional) An object containing segments + of text from search results with query-matching text highlighted using HTML + `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying segments + of text within the result that were identified as direct answers to the search + query. Currently, only the single answer with the highest confidence (if any) is + returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + + def __init__( + self, + id: str, + result_metadata: 'SearchResultMetadata', + *, + body: Optional[str] = None, + title: Optional[str] = None, + url: Optional[str] = None, + highlight: Optional['SearchResultHighlight'] = None, + answers: Optional[List['SearchResultAnswer']] = None, + ) -> None: + """ + Initialize a SearchResult object. + + :param str id: The unique identifier of the document in the Discovery + service collection. + This property is included in responses from search skills, which are + available only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search + result metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is + taken from an abstract, summary, or highlight field in the Discovery + service response, as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken + from a title or name field in the Discovery service response, as specified + in the search skill configuration. + :param str url: (optional) The URL of the original data object in its + native data source. + :param SearchResultHighlight highlight: (optional) An object containing + segments of text from search results with query-matching text highlighted + using HTML `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying + segments of text within the result that were identified as direct answers + to the search query. Currently, only the single answer with the highest + confidence (if any) is returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.id = id + self.result_metadata = result_metadata + self.body = body + self.title = title + self.url = url + self.highlight = highlight + self.answers = answers + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResult': + """Initialize a SearchResult object from a json dictionary.""" + args = {} + if (id := _dict.get('id')) is not None: + args['id'] = id + else: + raise ValueError( + 'Required property \'id\' not present in SearchResult JSON') + if (result_metadata := _dict.get('result_metadata')) is not None: + args['result_metadata'] = SearchResultMetadata.from_dict( + result_metadata) + else: + raise ValueError( + 'Required property \'result_metadata\' not present in SearchResult JSON' + ) + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = SearchResultHighlight.from_dict(highlight) + if (answers := _dict.get('answers')) is not None: + args['answers'] = [SearchResultAnswer.from_dict(v) for v in answers] + return cls(**args) + + @classmethod + 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: + _dict['id'] = self.id + if hasattr(self, + 'result_metadata') and self.result_metadata is not None: + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'highlight') and self.highlight is not None: + if isinstance(self.highlight, dict): + _dict['highlight'] = self.highlight + else: + _dict['highlight'] = self.highlight.to_dict() + if hasattr(self, 'answers') and self.answers is not None: + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this SearchResult object.""" + return json.dumps(self.to_dict(), indent=2) + + 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: 'SearchResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultAnswer: + """ + An object specifing a segment of text that was identified as a direct answer to the + search query. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned by the + Discovery service. + """ + + def __init__( + self, + text: str, + confidence: float, + ) -> None: + """ + Initialize a SearchResultAnswer object. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned + by the Discovery service. + """ + self.text = text + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': + """Initialize a SearchResultAnswer object from a json dictionary.""" + args = {} + if (text := _dict.get('text')) is not None: + args['text'] = text + else: + raise ValueError( + 'Required property \'text\' not present in SearchResultAnswer JSON' + ) + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + else: + raise ValueError( + 'Required property \'confidence\' not present in SearchResultAnswer JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultAnswer object from 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 + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + 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 SearchResultAnswer object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultAnswer') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchResultAnswer') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultHighlight: + """ + An object containing segments of text from search results with query-matching text + highlighted using HTML `` tags. + + :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 taken + from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments taken + from URLs in the search results, with query-matching substrings highlighted. + + This type supports additional properties of type List[str]. An array of strings + containing segments taken from a field in the search results that is not mapped to the + `body`, `title`, or `url` property, with query-matching substrings highlighted. The + property name is the name of the field in the Discovery collection. + """ + + # The set of defined properties for the class + _properties = frozenset(['body', 'title', 'url']) + + def __init__( + self, + *, + body: Optional[List[str]] = None, + title: Optional[List[str]] = None, + url: Optional[List[str]] = None, + **kwargs: Optional[List[str]], + ) -> None: + """ + Initialize a SearchResultHighlight object. + + :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 + taken from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments + taken from URLs in the search results, with query-matching substrings + highlighted. + :param List[str] **kwargs: (optional) An array of strings containing + segments taken from a field in the search results that is not mapped to the + `body`, `title`, or `url` property, with query-matching substrings + highlighted. The property name is the name of the field in the Discovery + collection. + """ + self.body = body + self.title = title + self.url = url + for k, v in kwargs.items(): + if k not in SearchResultHighlight._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[Foo]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + setattr(self, k, _v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': + """Initialize a SearchResultHighlight object from a json dictionary.""" + args = {} + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + args[k] = _v + return cls(**args) + + @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: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return the additional properties from this instance of SearchResultHighlight in the form of a dict.""" + _dict = {} + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of additional properties in this instance of SearchResultHighlight""" + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + delattr(self, k) + for k, v in _dict.items(): + if k not in SearchResultHighlight._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + setattr(self, k, _v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + def __str__(self) -> str: + """Return a `str` version of this SearchResultHighlight object.""" + return json.dumps(self.to_dict(), indent=2) + + 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: 'SearchResultHighlight') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultMetadata: + """ + An object containing search result metadata from the Discovery service. + + :param float confidence: (optional) The confidence score for the given result, + as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher score + indicates a greater match to the query parameters. + """ + + def __init__( + self, + *, + confidence: Optional[float] = None, + score: Optional[float] = None, + ) -> None: + """ + Initialize a SearchResultMetadata object. + + :param float confidence: (optional) The confidence score for the given + result, as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher + score indicates a greater match to the query parameters. + """ + self.confidence = confidence + self.score = score + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': + """Initialize a SearchResultMetadata object from a json dictionary.""" + args = {} + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (score := _dict.get('score')) is not None: + args['score'] = score + return cls(**args) + + @classmethod + 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: + _dict['confidence'] = self.confidence + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score + 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 SearchResultMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + 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: 'SearchResultMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettings: + """ + An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and are not + included in **Export skills** responses. + + :param SearchSettingsDiscovery discovery: Configuration settings for the Watson + Discovery service instance used by the search integration. + :param SearchSettingsMessages messages: The messages included with responses + from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between fields in + the Watson Discovery collection and properties in the search response. + :param SearchSettingsElasticSearch elastic_search: (optional) Configuration + settings for the Elasticsearch service used by the search integration. You can + provide either basic auth or apiKey auth. + :param SearchSettingsConversationalSearch conversational_search: (optional) + Configuration settings for conversational search. + :param SearchSettingsServerSideSearch server_side_search: (optional) + Configuration settings for the server-side search service used by the search + integration. You can provide either basic auth, apiKey auth or none. + :param SearchSettingsClientSideSearch client_side_search: (optional) + Configuration settings for the client-side search service or server-side search + service used by the search integration. + """ + + def __init__( + self, + discovery: 'SearchSettingsDiscovery', + messages: 'SearchSettingsMessages', + schema_mapping: 'SearchSettingsSchemaMapping', + *, + elastic_search: Optional['SearchSettingsElasticSearch'] = None, + conversational_search: Optional[ + 'SearchSettingsConversationalSearch'] = None, + server_side_search: Optional['SearchSettingsServerSideSearch'] = None, + client_side_search: Optional['SearchSettingsClientSideSearch'] = None, + ) -> None: + """ + Initialize a SearchSettings object. + + :param SearchSettingsDiscovery discovery: Configuration settings for the + Watson Discovery service instance used by the search integration. + :param SearchSettingsMessages messages: The messages included with + responses from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between + fields in the Watson Discovery collection and properties in the search + response. + :param SearchSettingsElasticSearch elastic_search: (optional) Configuration + settings for the Elasticsearch service used by the search integration. You + can provide either basic auth or apiKey auth. + :param SearchSettingsConversationalSearch conversational_search: (optional) + Configuration settings for conversational search. + :param SearchSettingsServerSideSearch server_side_search: (optional) + Configuration settings for the server-side search service used by the + search integration. You can provide either basic auth, apiKey auth or none. + :param SearchSettingsClientSideSearch client_side_search: (optional) + Configuration settings for the client-side search service or server-side + search service used by the search integration. + """ + self.discovery = discovery + self.messages = messages + self.schema_mapping = schema_mapping + self.elastic_search = elastic_search + self.conversational_search = conversational_search + self.server_side_search = server_side_search + self.client_side_search = client_side_search + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettings': + """Initialize a SearchSettings object from a json dictionary.""" + args = {} + if (discovery := _dict.get('discovery')) is not None: + args['discovery'] = SearchSettingsDiscovery.from_dict(discovery) + else: + raise ValueError( + 'Required property \'discovery\' not present in SearchSettings JSON' + ) + if (messages := _dict.get('messages')) is not None: + args['messages'] = SearchSettingsMessages.from_dict(messages) + else: + raise ValueError( + 'Required property \'messages\' not present in SearchSettings JSON' + ) + if (schema_mapping := _dict.get('schema_mapping')) is not None: + args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( + schema_mapping) + else: + raise ValueError( + 'Required property \'schema_mapping\' not present in SearchSettings JSON' + ) + if (elastic_search := _dict.get('elastic_search')) is not None: + args['elastic_search'] = SearchSettingsElasticSearch.from_dict( + elastic_search) + if (conversational_search := + _dict.get('conversational_search')) is not None: + args[ + 'conversational_search'] = SearchSettingsConversationalSearch.from_dict( + conversational_search) + if (server_side_search := _dict.get('server_side_search')) is not None: + args[ + 'server_side_search'] = SearchSettingsServerSideSearch.from_dict( + server_side_search) + if (client_side_search := _dict.get('client_side_search')) is not None: + args[ + 'client_side_search'] = SearchSettingsClientSideSearch.from_dict( + client_side_search) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettings object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'discovery') and self.discovery is not None: + if isinstance(self.discovery, dict): + _dict['discovery'] = self.discovery + else: + _dict['discovery'] = self.discovery.to_dict() + if hasattr(self, 'messages') and self.messages is not None: + if isinstance(self.messages, dict): + _dict['messages'] = self.messages + else: + _dict['messages'] = self.messages.to_dict() + if hasattr(self, 'schema_mapping') and self.schema_mapping is not None: + if isinstance(self.schema_mapping, dict): + _dict['schema_mapping'] = self.schema_mapping + else: + _dict['schema_mapping'] = self.schema_mapping.to_dict() + if hasattr(self, 'elastic_search') and self.elastic_search is not None: + if isinstance(self.elastic_search, dict): + _dict['elastic_search'] = self.elastic_search + else: + _dict['elastic_search'] = self.elastic_search.to_dict() + if hasattr(self, 'conversational_search' + ) and self.conversational_search is not None: + if isinstance(self.conversational_search, dict): + _dict['conversational_search'] = self.conversational_search + else: + _dict[ + 'conversational_search'] = self.conversational_search.to_dict( + ) + if hasattr( + self, + 'server_side_search') and self.server_side_search is not None: + if isinstance(self.server_side_search, dict): + _dict['server_side_search'] = self.server_side_search + else: + _dict['server_side_search'] = self.server_side_search.to_dict() + if hasattr( + self, + 'client_side_search') and self.client_side_search is not None: + if isinstance(self.client_side_search, dict): + _dict['client_side_search'] = self.client_side_search + else: + _dict['client_side_search'] = self.client_side_search.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 SearchSettings object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettings') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettings') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsClientSideSearch: + """ + Configuration settings for the client-side search service or server-side search + service used by the search integration. + + :param str filter: (optional) The filter string that is applied to the search + results. + :param dict metadata: (optional) The metadata object. + """ + + def __init__( + self, + *, + filter: Optional[str] = None, + metadata: Optional[dict] = None, + ) -> None: + """ + Initialize a SearchSettingsClientSideSearch object. + + :param str filter: (optional) The filter string that is applied to the + search results. + :param dict metadata: (optional) The metadata object. + """ + self.filter = filter + self.metadata = metadata + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsClientSideSearch': + """Initialize a SearchSettingsClientSideSearch object from a json dictionary.""" + args = {} + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsClientSideSearch object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + 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 SearchSettingsClientSideSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsClientSideSearch') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsClientSideSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsConversationalSearch: + """ + Configuration settings for conversational search. + + :param bool enabled: Whether to enable conversational search. + :param SearchSettingsConversationalSearchResponseLength response_length: + (optional) + :param SearchSettingsConversationalSearchSearchConfidence search_confidence: + (optional) + """ + + def __init__( + self, + enabled: bool, + *, + response_length: Optional[ + 'SearchSettingsConversationalSearchResponseLength'] = None, + search_confidence: Optional[ + 'SearchSettingsConversationalSearchSearchConfidence'] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearch object. + + :param bool enabled: Whether to enable conversational search. + :param SearchSettingsConversationalSearchResponseLength response_length: + (optional) + :param SearchSettingsConversationalSearchSearchConfidence + search_confidence: (optional) + """ + self.enabled = enabled + self.response_length = response_length + self.search_confidence = search_confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsConversationalSearch': + """Initialize a SearchSettingsConversationalSearch object from a json dictionary.""" + args = {} + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + else: + raise ValueError( + 'Required property \'enabled\' not present in SearchSettingsConversationalSearch JSON' + ) + if (response_length := _dict.get('response_length')) is not None: + args[ + 'response_length'] = SearchSettingsConversationalSearchResponseLength.from_dict( + response_length) + if (search_confidence := _dict.get('search_confidence')) is not None: + args[ + 'search_confidence'] = SearchSettingsConversationalSearchSearchConfidence.from_dict( + search_confidence) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearch object from 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 + if hasattr(self, + 'response_length') and self.response_length is not None: + if isinstance(self.response_length, dict): + _dict['response_length'] = self.response_length + else: + _dict['response_length'] = self.response_length.to_dict() + if hasattr(self, + 'search_confidence') and self.search_confidence is not None: + if isinstance(self.search_confidence, dict): + _dict['search_confidence'] = self.search_confidence + else: + _dict['search_confidence'] = self.search_confidence.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 SearchSettingsConversationalSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsConversationalSearch') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsConversationalSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsConversationalSearchResponseLength: + """ + SearchSettingsConversationalSearchResponseLength. + + :param str option: (optional) The response length option. It controls the length + of the generated response. + """ + + def __init__( + self, + *, + option: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearchResponseLength object. + + :param str option: (optional) The response length option. It controls the + length of the generated response. + """ + self.option = option + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'SearchSettingsConversationalSearchResponseLength': + """Initialize a SearchSettingsConversationalSearchResponseLength object from a json dictionary.""" + args = {} + if (option := _dict.get('option')) is not None: + args['option'] = option + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearchResponseLength object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'option') and self.option is not None: + _dict['option'] = self.option + 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 SearchSettingsConversationalSearchResponseLength object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'SearchSettingsConversationalSearchResponseLength') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, + other: 'SearchSettingsConversationalSearchResponseLength') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class OptionEnum(str, Enum): + """ + The response length option. It controls the length of the generated response. + """ + + CONCISE = 'concise' + MODERATE = 'moderate' + VERBOSE = 'verbose' + + +class SearchSettingsConversationalSearchSearchConfidence: + """ + SearchSettingsConversationalSearchSearchConfidence. + + :param str threshold: (optional) The search confidence threshold. + It controls the tendency for conversational search to produce “I don't know” + answers. + """ + + def __init__( + self, + *, + threshold: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearchSearchConfidence object. + + :param str threshold: (optional) The search confidence threshold. + It controls the tendency for conversational search to produce “I don't + know” answers. + """ + self.threshold = threshold + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'SearchSettingsConversationalSearchSearchConfidence': + """Initialize a SearchSettingsConversationalSearchSearchConfidence object from a json dictionary.""" + args = {} + if (threshold := _dict.get('threshold')) is not None: + args['threshold'] = threshold + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearchSearchConfidence object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'threshold') and self.threshold is not None: + _dict['threshold'] = self.threshold + 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 SearchSettingsConversationalSearchSearchConfidence object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'SearchSettingsConversationalSearchSearchConfidence' + ) -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__( + self, other: 'SearchSettingsConversationalSearchSearchConfidence' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ThresholdEnum(str, Enum): + """ + The search confidence threshold. + It controls the tendency for conversational search to produce “I don't know” + answers. + """ + + RARELY = 'rarely' + LESS_OFTEN = 'less_often' + MORE_OFTEN = 'more_often' + MOST_OFTEN = 'most_often' + + +class SearchSettingsDiscovery: + """ + Configuration settings for the Watson Discovery service instance used by the search + integration. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param int max_primary_results: (optional) The maximum number of primary results + to include in the response. + :param int max_total_results: (optional) The maximum total number of primary and + additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence threshold + for included results. Any results with a confidence below this threshold will be + discarded. + :param bool highlight: (optional) Whether to include the most relevant passages + of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding feature + to emphasize answers within highlighted passages. This property is ignored if + **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + """ + + def __init__( + self, + instance_id: str, + project_id: str, + url: str, + authentication: 'SearchSettingsDiscoveryAuthentication', + *, + max_primary_results: Optional[int] = None, + max_total_results: Optional[int] = None, + confidence_threshold: Optional[float] = None, + highlight: Optional[bool] = None, + find_answers: Optional[bool] = None, + ) -> None: + """ + Initialize a SearchSettingsDiscovery object. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + :param int max_primary_results: (optional) The maximum number of primary + results to include in the response. + :param int max_total_results: (optional) The maximum total number of + primary and additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence + threshold for included results. Any results with a confidence below this + threshold will be discarded. + :param bool highlight: (optional) Whether to include the most relevant + passages of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding + feature to emphasize answers within highlighted passages. This property is + ignored if **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.instance_id = instance_id + self.project_id = project_id + self.url = url + self.max_primary_results = max_primary_results + self.max_total_results = max_total_results + self.confidence_threshold = confidence_threshold + self.highlight = highlight + self.find_answers = find_answers + self.authentication = authentication + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': + """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + args = {} + if (instance_id := _dict.get('instance_id')) is not None: + args['instance_id'] = instance_id + else: + raise ValueError( + 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' + ) + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id + else: + raise ValueError( + 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' + ) + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsDiscovery JSON' + ) + if (max_primary_results := + _dict.get('max_primary_results')) is not None: + args['max_primary_results'] = max_primary_results + if (max_total_results := _dict.get('max_total_results')) is not None: + args['max_total_results'] = max_total_results + if (confidence_threshold := + _dict.get('confidence_threshold')) is not None: + args['confidence_threshold'] = confidence_threshold + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = highlight + if (find_answers := _dict.get('find_answers')) is not None: + args['find_answers'] = find_answers + if (authentication := _dict.get('authentication')) is not None: + args[ + 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( + authentication) + else: + raise ValueError( + 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'instance_id') and self.instance_id is not None: + _dict['instance_id'] = self.instance_id + if hasattr(self, 'project_id') and self.project_id is not None: + _dict['project_id'] = self.project_id + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr( + self, + 'max_primary_results') and self.max_primary_results is not None: + _dict['max_primary_results'] = self.max_primary_results + if hasattr(self, + 'max_total_results') and self.max_total_results is not None: + _dict['max_total_results'] = self.max_total_results + if hasattr(self, 'confidence_threshold' + ) and self.confidence_threshold is not None: + _dict['confidence_threshold'] = self.confidence_threshold + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'find_answers') and self.find_answers is not None: + _dict['find_answers'] = self.find_answers + if hasattr(self, 'authentication') and self.authentication is not None: + if isinstance(self.authentication, dict): + _dict['authentication'] = self.authentication + else: + _dict['authentication'] = self.authentication.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 SearchSettingsDiscovery object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscovery') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsDiscovery') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsDiscoveryAuthentication: + """ + Authentication information for the Watson Discovery service. For more information, see + the [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + + def __init__( + self, + *, + basic: Optional[str] = None, + bearer: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsDiscoveryAuthentication object. + + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + self.basic = basic + self.bearer = bearer + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': + """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + args = {} + if (basic := _dict.get('basic')) is not None: + args['basic'] = basic + if (bearer := _dict.get('bearer')) is not None: + args['bearer'] = bearer + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'basic') and self.basic is not None: + _dict['basic'] = self.basic + if hasattr(self, 'bearer') and self.bearer is not None: + _dict['bearer'] = self.bearer + 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 SearchSettingsDiscoveryAuthentication object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsElasticSearch: + """ + Configuration settings for the Elasticsearch service used by the search integration. + You can provide either basic auth or apiKey auth. + + :param str url: The URL for the Elasticsearch service. + :param str port: The port number for the Elasticsearch service URL. + **Note:** It can be omitted if a port number is appended to the URL. + :param str username: (optional) The username of the basic authentication method. + :param str password: (optional) The password of the basic authentication method. + The credentials are not returned due to security reasons. + :param str index: The Elasticsearch index to use for the search integration. + :param List[object] filter: (optional) An array of filters that can be applied + to the search results via the `$FILTER` variable in the `query_body`.For more + information, see [Elasticsearch filter + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/filter-search-results.html). + :param dict query_body: (optional) The Elasticsearch query object. For more + information, see [Elasticsearch search API + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html). + :param str managed_index: (optional) The Elasticsearch index for uploading + documents. It is created automatically when the upload document option is + selected from the user interface. + :param str apikey: (optional) The API key of the apiKey authentication method. + Use either basic auth or apiKey auth. The credentials are not returned due to + security reasons. + """ + + def __init__( + self, + url: str, + port: str, + index: str, + *, + username: Optional[str] = None, + password: Optional[str] = None, + filter: Optional[List[object]] = None, + query_body: Optional[dict] = None, + managed_index: Optional[str] = None, + apikey: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsElasticSearch object. + + :param str url: The URL for the Elasticsearch service. + :param str port: The port number for the Elasticsearch service URL. + **Note:** It can be omitted if a port number is appended to the URL. + :param str index: The Elasticsearch index to use for the search + integration. + :param str username: (optional) The username of the basic authentication + method. + :param str password: (optional) The password of the basic authentication + method. The credentials are not returned due to security reasons. + :param List[object] filter: (optional) An array of filters that can be + applied to the search results via the `$FILTER` variable in the + `query_body`.For more information, see [Elasticsearch filter + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/filter-search-results.html). + :param dict query_body: (optional) The Elasticsearch query object. For more + information, see [Elasticsearch search API + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html). + :param str managed_index: (optional) The Elasticsearch index for uploading + documents. It is created automatically when the upload document option is + selected from the user interface. + :param str apikey: (optional) The API key of the apiKey authentication + method. Use either basic auth or apiKey auth. The credentials are not + returned due to security reasons. + """ + self.url = url + self.port = port + self.username = username + self.password = password + self.index = index + self.filter = filter + self.query_body = query_body + self.managed_index = managed_index + self.apikey = apikey + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsElasticSearch': + """Initialize a SearchSettingsElasticSearch object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsElasticSearch JSON' + ) + if (port := _dict.get('port')) is not None: + args['port'] = port + else: + raise ValueError( + 'Required property \'port\' not present in SearchSettingsElasticSearch JSON' + ) + if (username := _dict.get('username')) is not None: + args['username'] = username + if (password := _dict.get('password')) is not None: + args['password'] = password + if (index := _dict.get('index')) is not None: + args['index'] = index + else: + raise ValueError( + 'Required property \'index\' not present in SearchSettingsElasticSearch JSON' + ) + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (query_body := _dict.get('query_body')) is not None: + args['query_body'] = query_body + if (managed_index := _dict.get('managed_index')) is not None: + args['managed_index'] = managed_index + if (apikey := _dict.get('apikey')) is not None: + args['apikey'] = apikey + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsElasticSearch object from 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: + _dict['url'] = self.url + if hasattr(self, 'port') and self.port is not None: + _dict['port'] = self.port + if hasattr(self, 'username') and self.username is not None: + _dict['username'] = self.username + if hasattr(self, 'password') and self.password is not None: + _dict['password'] = self.password + if hasattr(self, 'index') and self.index is not None: + _dict['index'] = self.index + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'query_body') and self.query_body is not None: + _dict['query_body'] = self.query_body + if hasattr(self, 'managed_index') and self.managed_index is not None: + _dict['managed_index'] = self.managed_index + if hasattr(self, 'apikey') and self.apikey is not None: + _dict['apikey'] = self.apikey + 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 SearchSettingsElasticSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsElasticSearch') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsElasticSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsMessages: + """ + The messages included with responses from the search integration. + + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is no + result from the query. + """ + + def __init__( + self, + success: str, + error: str, + no_result: str, + ) -> None: + """ + Initialize a SearchSettingsMessages object. + + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is + no result from the query. + """ + self.success = success + self.error = error + self.no_result = no_result + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': + """Initialize a SearchSettingsMessages object from a json dictionary.""" + args = {} + if (success := _dict.get('success')) is not None: + args['success'] = success + else: + raise ValueError( + 'Required property \'success\' not present in SearchSettingsMessages JSON' + ) + if (error := _dict.get('error')) is not None: + args['error'] = error + else: + raise ValueError( + 'Required property \'error\' not present in SearchSettingsMessages JSON' + ) + if (no_result := _dict.get('no_result')) is not None: + args['no_result'] = no_result + else: + raise ValueError( + 'Required property \'no_result\' not present in SearchSettingsMessages JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsMessages object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'success') and self.success is not None: + _dict['success'] = self.success + if hasattr(self, 'error') and self.error is not None: + _dict['error'] = self.error + if hasattr(self, 'no_result') and self.no_result is not None: + _dict['no_result'] = self.no_result + 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 SearchSettingsMessages object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsMessages') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsMessages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsSchemaMapping: + """ + The mapping between fields in the Watson Discovery collection and properties in the + search response. + + :param str url: The field in the collection to map to the **url** property of + the response. + :param str body: The field in the collection to map to the **body** property in + the response. + :param str title: The field in the collection to map to the **title** property + for the schema. + """ + + def __init__( + self, + url: str, + body: str, + title: str, + ) -> None: + """ + Initialize a SearchSettingsSchemaMapping object. + + :param str url: The field in the collection to map to the **url** property + of the response. + :param str body: The field in the collection to map to the **body** + property in the response. + :param str title: The field in the collection to map to the **title** + property for the schema. + """ + self.url = url + self.body = body + self.title = title + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': + """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' + ) + if (body := _dict.get('body')) is not None: + args['body'] = body + else: + raise ValueError( + 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' + ) + if (title := _dict.get('title')) is not None: + args['title'] = title + else: + raise ValueError( + 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsSchemaMapping object from 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: + _dict['url'] = self.url + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + 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 SearchSettingsSchemaMapping object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsSchemaMapping') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsSchemaMapping') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsServerSideSearch: + """ + Configuration settings for the server-side search service used by the search + integration. You can provide either basic auth, apiKey auth or none. + + :param str url: The URL of the server-side search service. + :param str port: (optional) The port number of the server-side search service. + :param str username: (optional) The username of the basic authentication method. + :param str password: (optional) The password of the basic authentication method. + The credentials are not returned due to security reasons. + :param str filter: (optional) The filter string that is applied to the search + results. + :param dict metadata: (optional) The metadata object. + :param str apikey: (optional) The API key of the apiKey authentication method. + The credentails are not returned due to security reasons. + :param bool no_auth: (optional) To clear previous auth, specify `no_auth = + true`. + :param str auth_type: (optional) The authorization type that is used. + """ + + def __init__( + self, + url: str, + *, + port: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + filter: Optional[str] = None, + metadata: Optional[dict] = None, + apikey: Optional[str] = None, + no_auth: Optional[bool] = None, + auth_type: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsServerSideSearch object. + + :param str url: The URL of the server-side search service. + :param str port: (optional) The port number of the server-side search + service. + :param str username: (optional) The username of the basic authentication + method. + :param str password: (optional) The password of the basic authentication + method. The credentials are not returned due to security reasons. + :param str filter: (optional) The filter string that is applied to the + search results. + :param dict metadata: (optional) The metadata object. + :param str apikey: (optional) The API key of the apiKey authentication + method. The credentails are not returned due to security reasons. + :param bool no_auth: (optional) To clear previous auth, specify `no_auth = + true`. + :param str auth_type: (optional) The authorization type that is used. + """ + self.url = url + self.port = port + self.username = username + self.password = password + self.filter = filter + self.metadata = metadata + self.apikey = apikey + self.no_auth = no_auth + self.auth_type = auth_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsServerSideSearch': + """Initialize a SearchSettingsServerSideSearch object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsServerSideSearch JSON' + ) + if (port := _dict.get('port')) is not None: + args['port'] = port + if (username := _dict.get('username')) is not None: + args['username'] = username + if (password := _dict.get('password')) is not None: + args['password'] = password + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (apikey := _dict.get('apikey')) is not None: + args['apikey'] = apikey + if (no_auth := _dict.get('no_auth')) is not None: + args['no_auth'] = no_auth + if (auth_type := _dict.get('auth_type')) is not None: + args['auth_type'] = auth_type + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsServerSideSearch object from 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: + _dict['url'] = self.url + if hasattr(self, 'port') and self.port is not None: + _dict['port'] = self.port + if hasattr(self, 'username') and self.username is not None: + _dict['username'] = self.username + if hasattr(self, 'password') and self.password is not None: + _dict['password'] = self.password + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + if hasattr(self, 'apikey') and self.apikey is not None: + _dict['apikey'] = self.apikey + if hasattr(self, 'no_auth') and self.no_auth is not None: + _dict['no_auth'] = self.no_auth + if hasattr(self, 'auth_type') and self.auth_type is not None: + _dict['auth_type'] = self.auth_type + 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 SearchSettingsServerSideSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsServerSideSearch') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSettingsServerSideSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class AuthTypeEnum(str, Enum): + """ + The authorization type that is used. + """ + + BASIC = 'basic' + APIKEY = 'apikey' + NONE = 'none' + + +class SearchSkillWarning: + """ + A warning describing an error in the search skill configuration. + + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. + """ + + def __init__( + self, + *, + code: Optional[str] = None, + path: Optional[str] = None, + message: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSkillWarning object. + + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. + """ + self.code = code + self.path = path + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': + """Initialize a SearchSkillWarning object from a json dictionary.""" + args = {} + if (code := _dict.get('code')) is not None: + args['code'] = code + if (path := _dict.get('path')) is not None: + args['path'] = path + if (message := _dict.get('message')) is not None: + args['message'] = message + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSkillWarning object from 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: + _dict['code'] = self.code + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + 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 SearchSkillWarning object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSkillWarning') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'SearchSkillWarning') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SessionResponse: + """ + SessionResponse. + + :param str session_id: The session ID. + """ + + def __init__( + self, + session_id: str, + ) -> None: + """ + Initialize a SessionResponse object. + + :param str session_id: The session ID. + """ + self.session_id = session_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SessionResponse': + """Initialize a SessionResponse object from a json dictionary.""" + args = {} + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id + else: + raise ValueError( + 'Required property \'session_id\' not present in SessionResponse JSON' + ) + return cls(**args) + + @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 _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: '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: 'SessionResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Skill: + """ + Skill. + + :param str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :param str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :param str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :param str language: The language of the skill. + :param str type: The type of skill. + """ + + def __init__( + self, + language: str, + type: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, + ) -> None: + """ + Initialize a Skill object. - :param str calendar_type: (optional) The calendar used to represent a - recognized date (for example, `Gregorian`). - :param str datetime_link: (optional) A unique identifier used to associate - a recognized time and date. If the user input contains a date and time that - are mentioned together (for example, `Today at 5`, the same - **datetime_link** value is returned for both the `@sys-date` and - `@sys-time` entities). - :param str festival: (optional) A locale-specific holiday name (such as - `thanksgiving` or `christmas`). This property is included when a - `@sys-date` entity is recognized based on a holiday name in the user input. - :param str granularity: (optional) The precision or duration of a time - range specified by a recognized `@sys-time` or `@sys-date` entity. - :param str range_link: (optional) A unique identifier used to associate - multiple recognized `@sys-date`, `@sys-time`, or `@sys-number` entities - that are recognized as a range of values in the user's input (for example, - `from July 4 until July 14` or `from 20 to 25`). - :param str range_modifier: (optional) The word in the user input that - indicates that a `sys-date` or `sys-time` entity is part of an implied - range where only one date or time is specified (for example, `since` or - `until`). - :param float relative_day: (optional) A recognized mention of a relative - day, represented numerically as an offset from the current date (for - example, `-1` for `yesterday` or `10` for `in ten days`). - :param float relative_month: (optional) A recognized mention of a relative - month, represented numerically as an offset from the current month (for - example, `1` for `next month` or `-3` for `three months ago`). - :param float relative_week: (optional) A recognized mention of a relative - week, represented numerically as an offset from the current week (for - example, `2` for `in two weeks` or `-1` for `last week). - :param float relative_weekend: (optional) A recognized mention of a - relative date range for a weekend, represented numerically as an offset - from the current weekend (for example, `0` for `this weekend` or `-1` for - `last weekend`). - :param float relative_year: (optional) A recognized mention of a relative - year, represented numerically as an offset from the current year (for - example, `1` for `next year` or `-5` for `five years ago`). - :param float specific_day: (optional) A recognized mention of a specific - date, represented numerically as the date within the month (for example, - `30` for `June 30`.). - :param str specific_day_of_week: (optional) A recognized mention of a - specific day of the week as a lowercase string (for example, `monday`). - :param float specific_month: (optional) A recognized mention of a specific - month, represented numerically (for example, `7` for `July`). - :param float specific_quarter: (optional) A recognized mention of a - specific quarter, represented numerically (for example, `3` for `the third - quarter`). - :param float specific_year: (optional) A recognized mention of a specific - year (for example, `2016`). - :param float numeric_value: (optional) A recognized numeric value, - represented as an integer or double. - :param str subtype: (optional) The type of numeric value recognized in the - user input (`integer` or `rational`). - :param str part_of_day: (optional) A recognized term for a time that was - mentioned as a part of the day in the user's input (for example, `morning` - or `afternoon`). - :param float relative_hour: (optional) A recognized mention of a relative - hour, represented numerically as an offset from the current hour (for - example, `3` for `in three hours` or `-1` for `an hour ago`). - :param float relative_minute: (optional) A recognized mention of a relative - time, represented numerically as an offset in minutes from the current time - (for example, `5` for `in five minutes` or `-15` for `fifteen minutes - ago`). - :param float relative_second: (optional) A recognized mention of a relative - time, represented numerically as an offset in seconds from the current time - (for example, `10` for `in ten seconds` or `-30` for `thirty seconds ago`). - :param float specific_hour: (optional) A recognized specific hour mentioned - as part of a time value (for example, `10` for `10:15 AM`.). - :param float specific_minute: (optional) A recognized specific minute - mentioned as part of a time value (for example, `15` for `10:15 AM`.). - :param float specific_second: (optional) A recognized specific second - mentioned as part of a time value (for example, `30` for `10:15:30 AM`.). - :param str timezone: (optional) A recognized time zone mentioned as part of - a time value (for example, `EST`). + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. """ - self.calendar_type = calendar_type - self.datetime_link = datetime_link - self.festival = festival - self.granularity = granularity - self.range_link = range_link - self.range_modifier = range_modifier - self.relative_day = relative_day - self.relative_month = relative_month - self.relative_week = relative_week - self.relative_weekend = relative_weekend - self.relative_year = relative_year - self.specific_day = specific_day - self.specific_day_of_week = specific_day_of_week - self.specific_month = specific_month - self.specific_quarter = specific_quarter - self.specific_year = specific_year - self.numeric_value = numeric_value - self.subtype = subtype - self.part_of_day = part_of_day - self.relative_hour = relative_hour - self.relative_minute = relative_minute - self.relative_second = relative_second - self.specific_hour = specific_hour - self.specific_minute = specific_minute - self.specific_second = specific_second - self.timezone = timezone + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Skill': + """Initialize a Skill object from a json dictionary.""" args = {} - if (calendar_type := _dict.get('calendar_type')) is not None: - args['calendar_type'] = calendar_type - if (datetime_link := _dict.get('datetime_link')) is not None: - args['datetime_link'] = datetime_link - if (festival := _dict.get('festival')) is not None: - args['festival'] = festival - if (granularity := _dict.get('granularity')) is not None: - args['granularity'] = granularity - if (range_link := _dict.get('range_link')) is not None: - args['range_link'] = range_link - if (range_modifier := _dict.get('range_modifier')) is not None: - args['range_modifier'] = range_modifier - if (relative_day := _dict.get('relative_day')) is not None: - args['relative_day'] = relative_day - if (relative_month := _dict.get('relative_month')) is not None: - args['relative_month'] = relative_month - if (relative_week := _dict.get('relative_week')) is not None: - args['relative_week'] = relative_week - if (relative_weekend := _dict.get('relative_weekend')) is not None: - args['relative_weekend'] = relative_weekend - if (relative_year := _dict.get('relative_year')) is not None: - args['relative_year'] = relative_year - if (specific_day := _dict.get('specific_day')) is not None: - args['specific_day'] = specific_day - if (specific_day_of_week := - _dict.get('specific_day_of_week')) is not None: - args['specific_day_of_week'] = specific_day_of_week - if (specific_month := _dict.get('specific_month')) is not None: - args['specific_month'] = specific_month - if (specific_quarter := _dict.get('specific_quarter')) is not None: - args['specific_quarter'] = specific_quarter - if (specific_year := _dict.get('specific_year')) is not None: - args['specific_year'] = specific_year - if (numeric_value := _dict.get('numeric_value')) is not None: - args['numeric_value'] = numeric_value - if (subtype := _dict.get('subtype')) is not None: - args['subtype'] = subtype - if (part_of_day := _dict.get('part_of_day')) is not None: - args['part_of_day'] = part_of_day - if (relative_hour := _dict.get('relative_hour')) is not None: - args['relative_hour'] = relative_hour - if (relative_minute := _dict.get('relative_minute')) is not None: - args['relative_minute'] = relative_minute - if (relative_second := _dict.get('relative_second')) is not None: - args['relative_second'] = relative_second - if (specific_hour := _dict.get('specific_hour')) is not None: - args['specific_hour'] = specific_hour - if (specific_minute := _dict.get('specific_minute')) is not None: - args['specific_minute'] = specific_minute - if (specific_second := _dict.get('specific_second')) is not None: - args['specific_second'] = specific_second - if (timezone := _dict.get('timezone')) is not None: - args['timezone'] = timezone + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in warnings + ] + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in Skill JSON') + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in Skill JSON') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + """Initialize a Skill object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'calendar_type') and self.calendar_type is not None: - _dict['calendar_type'] = self.calendar_type - if hasattr(self, 'datetime_link') and self.datetime_link is not None: - _dict['datetime_link'] = self.datetime_link - if hasattr(self, 'festival') and self.festival is not None: - _dict['festival'] = self.festival - if hasattr(self, 'granularity') and self.granularity is not None: - _dict['granularity'] = self.granularity - if hasattr(self, 'range_link') and self.range_link is not None: - _dict['range_link'] = self.range_link - if hasattr(self, 'range_modifier') and self.range_modifier is not None: - _dict['range_modifier'] = self.range_modifier - if hasattr(self, 'relative_day') and self.relative_day is not None: - _dict['relative_day'] = self.relative_day - if hasattr(self, 'relative_month') and self.relative_month is not None: - _dict['relative_month'] = self.relative_month - if hasattr(self, 'relative_week') and self.relative_week is not None: - _dict['relative_week'] = self.relative_week - if hasattr(self, - 'relative_weekend') and self.relative_weekend is not None: - _dict['relative_weekend'] = self.relative_weekend - if hasattr(self, 'relative_year') and self.relative_year is not None: - _dict['relative_year'] = self.relative_year - if hasattr(self, 'specific_day') and self.specific_day is not None: - _dict['specific_day'] = self.specific_day - if hasattr(self, 'specific_day_of_week' - ) and self.specific_day_of_week is not None: - _dict['specific_day_of_week'] = self.specific_day_of_week - if hasattr(self, 'specific_month') and self.specific_month is not None: - _dict['specific_month'] = self.specific_month - if hasattr(self, - 'specific_quarter') and self.specific_quarter is not None: - _dict['specific_quarter'] = self.specific_quarter - if hasattr(self, 'specific_year') and self.specific_year is not None: - _dict['specific_year'] = self.specific_year - if hasattr(self, 'numeric_value') and self.numeric_value is not None: - _dict['numeric_value'] = self.numeric_value - if hasattr(self, 'subtype') and self.subtype is not None: - _dict['subtype'] = self.subtype - if hasattr(self, 'part_of_day') and self.part_of_day is not None: - _dict['part_of_day'] = self.part_of_day - if hasattr(self, 'relative_hour') and self.relative_hour is not None: - _dict['relative_hour'] = self.relative_hour - if hasattr(self, - 'relative_minute') and self.relative_minute is not None: - _dict['relative_minute'] = self.relative_minute - if hasattr(self, - 'relative_second') and self.relative_second is not None: - _dict['relative_second'] = self.relative_second - if hasattr(self, 'specific_hour') and self.specific_hour is not None: - _dict['specific_hour'] = self.specific_hour + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') if hasattr(self, - 'specific_minute') and self.specific_minute is not None: - _dict['specific_minute'] = self.specific_minute + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') if hasattr(self, - 'specific_second') and self.specific_second is not None: - _dict['specific_second'] = self.specific_second - if hasattr(self, 'timezone') and self.timezone is not None: - _dict['timezone'] = self.timezone + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -8149,75 +13223,265 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityInterpretation object.""" + """Return a `str` version of this Skill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + def __eq__(self, other: 'Skill') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntityInterpretation') -> bool: + def __ne__(self, other: 'Skill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class GranularityEnum(str, Enum): + class StatusEnum(str, Enum): """ - The precision or duration of a time range specified by a recognized `@sys-time` or - `@sys-date` entity. + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. """ - DAY = 'day' - FORTNIGHT = 'fortnight' - HOUR = 'hour' - INSTANT = 'instant' - MINUTE = 'minute' - MONTH = 'month' - QUARTER = 'quarter' - SECOND = 'second' - WEEK = 'week' - WEEKEND = 'weekend' - YEAR = 'year' + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' + + class TypeEnum(str, Enum): + """ + The type of skill. + """ + + ACTION = 'action' + DIALOG = 'dialog' + SEARCH = 'search' -class RuntimeEntityRole: +class SkillImport: """ - An object describing the role played by a system entity that is specifies the - beginning or end of a range recognized in the user input. This property is included - only if the new system entities are enabled for the skill. + SkillImport. - :param str type: (optional) The relationship of the entity to the range. + :param str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :param str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :param str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :param str language: The language of the skill. + :param str type: The type of skill. """ def __init__( self, + language: str, + type: str, *, - type: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, ) -> None: """ - Initialize a RuntimeEntityRole object. + Initialize a SkillImport object. - :param str type: (optional) The relationship of the entity to the range. + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. """ + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': - """Initialize a RuntimeEntityRole object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillImport': + """Initialize a SkillImport object from a json dictionary.""" args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in warnings + ] + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in SkillImport JSON' + ) if (type := _dict.get('type')) is not None: args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in SkillImport JSON') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityRole object from a json dictionary.""" + """Initialize a SkillImport object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') + if hasattr(self, + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type return _dict @@ -8227,101 +13491,122 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityRole object.""" + """Return a `str` version of this SkillImport object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityRole') -> bool: + def __eq__(self, other: 'SkillImport') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeEntityRole') -> bool: + def __ne__(self, other: 'SkillImport') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' + class TypeEnum(str, Enum): """ - The relationship of the entity to the range. + The type of skill. """ - DATE_FROM = 'date_from' - DATE_TO = 'date_to' - NUMBER_FROM = 'number_from' - NUMBER_TO = 'number_to' - TIME_FROM = 'time_from' - TIME_TO = 'time_to' + ACTION = 'action' + DIALOG = 'dialog' -class RuntimeIntent: +class SkillsAsyncRequestStatus: """ - An intent identified in the user input. + SkillsAsyncRequestStatus. - :param str intent: The name of the recognized intent. - :param float confidence: (optional) A decimal percentage that represents - confidence in the intent. If you are specifying an intent as part of a request, - but you do not have a calculated confidence value, specify `1`. - :param str skill: (optional) The skill that identified the intent. Currently, - the only possible values are `main skill` for the dialog skill (if enabled) and - `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and an - action skill. + :param str assistant_id: (optional) The assistant ID of the assistant. + :param str status: (optional) The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. """ def __init__( self, - intent: str, *, - confidence: Optional[float] = None, - skill: Optional[str] = None, + assistant_id: Optional[str] = None, + status: Optional[str] = None, + status_description: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, ) -> None: """ - Initialize a RuntimeIntent object. + Initialize a SkillsAsyncRequestStatus object. - :param str intent: The name of the recognized intent. - :param float confidence: (optional) A decimal percentage that represents - confidence in the intent. If you are specifying an intent as part of a - request, but you do not have a calculated confidence value, specify `1`. - :param str skill: (optional) The skill that identified the intent. - Currently, the only possible values are `main skill` for the dialog skill - (if enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and - an action skill. """ - self.intent = intent - self.confidence = confidence - self.skill = skill + self.assistant_id = assistant_id + self.status = status + self.status_description = status_description + self.status_errors = status_errors @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': - """Initialize a RuntimeIntent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" args = {} - if (intent := _dict.get('intent')) is not None: - args['intent'] = intent - else: - raise ValueError( - 'Required property \'intent\' not present in RuntimeIntent JSON' - ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (skill := _dict.get('skill')) is not None: - args['skill'] = skill + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeIntent object from a json dictionary.""" + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'intent') and self.intent is not None: - _dict['intent'] = self.intent - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'skill') and self.skill is not None: - _dict['skill'] = self.skill + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list return _dict def _to_dict(self): @@ -8329,255 +13614,105 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeIntent object.""" + """Return a `str` version of this SkillsAsyncRequestStatus object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeIntent') -> bool: + def __eq__(self, other: 'SkillsAsyncRequestStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'RuntimeIntent') -> bool: + def __ne__(self, other: 'SkillsAsyncRequestStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - -class RuntimeResponseGeneric: - """ - RuntimeResponseGeneric. - - """ - - def __init__(self,) -> None: + class StatusEnum(str, Enum): """ - Initialize a RuntimeResponseGeneric object. - + The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - return cls.from_dict(_dict) - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' - mapping[ - 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' - mapping[ - 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' - mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' - mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' - mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' - mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' - mapping[ - 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' - mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' - mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' - mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' - mapping[ - 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' - mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' - disc_value = _dict.get('response_type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric 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) + AVAILABLE = 'Available' + COMPLETED = 'Completed' + FAILED = 'Failed' + PROCESSING = 'Processing' -class SearchResult: +class SkillsExport: """ - SearchResult. + SkillsExport. - :param str id: The unique identifier of the document in the Discovery service - collection. - This property is included in responses from search skills, which are available - only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search result - metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is taken - from an abstract, summary, or highlight field in the Discovery service response, - as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken from - a title or name field in the Discovery service response, as specified in the - search skill configuration. - :param str url: (optional) The URL of the original data object in its native - data source. - :param SearchResultHighlight highlight: (optional) An object containing segments - of text from search results with query-matching text highlighted using HTML - `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying segments - of text within the result that were identified as direct answers to the search - query. Currently, only the single answer with the highest confidence (if any) is - returned. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. + :param List[Skill] assistant_skills: An array of objects describing the skills + for the assistant. Included in responses only if **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills for + the assistant. Included in responses only if **status**=`Available`. """ def __init__( self, - id: str, - result_metadata: 'SearchResultMetadata', - *, - body: Optional[str] = None, - title: Optional[str] = None, - url: Optional[str] = None, - highlight: Optional['SearchResultHighlight'] = None, - answers: Optional[List['SearchResultAnswer']] = None, + assistant_skills: List['Skill'], + assistant_state: 'AssistantState', ) -> None: """ - Initialize a SearchResult object. + Initialize a SkillsExport object. - :param str id: The unique identifier of the document in the Discovery - service collection. - This property is included in responses from search skills, which are - available only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search - result metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is - taken from an abstract, summary, or highlight field in the Discovery - service response, as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken - from a title or name field in the Discovery service response, as specified - in the search skill configuration. - :param str url: (optional) The URL of the original data object in its - native data source. - :param SearchResultHighlight highlight: (optional) An object containing - segments of text from search results with query-matching text highlighted - using HTML `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying - segments of text within the result that were identified as direct answers - to the search query. Currently, only the single answer with the highest - confidence (if any) is returned. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. + :param List[Skill] assistant_skills: An array of objects describing the + skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. """ - self.id = id - self.result_metadata = result_metadata - self.body = body - self.title = title - self.url = url - self.highlight = highlight - self.answers = answers + self.assistant_skills = assistant_skills + self.assistant_state = assistant_state @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResult': - """Initialize a SearchResult object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillsExport': + """Initialize a SkillsExport object from a json dictionary.""" args = {} - if (id := _dict.get('id')) is not None: - args['id'] = id + if (assistant_skills := _dict.get('assistant_skills')) is not None: + args['assistant_skills'] = [ + Skill.from_dict(v) for v in assistant_skills + ] else: raise ValueError( - 'Required property \'id\' not present in SearchResult JSON') - if (result_metadata := _dict.get('result_metadata')) is not None: - args['result_metadata'] = SearchResultMetadata.from_dict( - result_metadata) + 'Required property \'assistant_skills\' not present in SkillsExport JSON' + ) + if (assistant_state := _dict.get('assistant_state')) is not None: + args['assistant_state'] = AssistantState.from_dict(assistant_state) else: raise ValueError( - 'Required property \'result_metadata\' not present in SearchResult JSON' + 'Required property \'assistant_state\' not present in SkillsExport JSON' ) - if (body := _dict.get('body')) is not None: - args['body'] = body - if (title := _dict.get('title')) is not None: - args['title'] = title - if (url := _dict.get('url')) is not None: - args['url'] = url - if (highlight := _dict.get('highlight')) is not None: - args['highlight'] = SearchResultHighlight.from_dict(highlight) - if (answers := _dict.get('answers')) is not None: - args['answers'] = [SearchResultAnswer.from_dict(v) for v in answers] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResult object from a json dictionary.""" + """Initialize a SkillsExport object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'id') and self.id is not None: - _dict['id'] = self.id if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - if isinstance(self.result_metadata, dict): - _dict['result_metadata'] = self.result_metadata - else: - _dict['result_metadata'] = self.result_metadata.to_dict() - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'highlight') and self.highlight is not None: - if isinstance(self.highlight, dict): - _dict['highlight'] = self.highlight - else: - _dict['highlight'] = self.highlight.to_dict() - if hasattr(self, 'answers') and self.answers is not None: - answers_list = [] - for v in self.answers: + 'assistant_skills') and self.assistant_skills is not None: + assistant_skills_list = [] + for v in self.assistant_skills: if isinstance(v, dict): - answers_list.append(v) + assistant_skills_list.append(v) else: - answers_list.append(v.to_dict()) - _dict['answers'] = answers_list + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, + 'assistant_state') and self.assistant_state is not None: + if isinstance(self.assistant_state, dict): + _dict['assistant_state'] = self.assistant_state + else: + _dict['assistant_state'] = self.assistant_state.to_dict() return _dict def _to_dict(self): @@ -8585,75 +13720,141 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResult object.""" + """Return a `str` version of this SkillsExport object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResult') -> bool: + def __eq__(self, other: 'SkillsExport') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResult') -> bool: + def __ne__(self, other: 'SkillsExport') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultAnswer: +class StatefulMessageResponse: """ - An object specifing a segment of text that was identified as a direct answer to the - search query. + A response from the watsonx Assistant service. - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned by the - Discovery service. + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. """ def __init__( self, - text: str, - confidence: float, + output: 'MessageOutput', + user_id: str, + *, + context: Optional['MessageContext'] = None, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, ) -> None: """ - Initialize a SearchResultAnswer object. + Initialize a StatefulMessageResponse object. - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned - by the Discovery service. + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. """ - self.text = text - self.confidence = confidence + self.output = output + self.context = context + self.user_id = user_id + self.masked_output = masked_output + self.masked_input = masked_input @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': - """Initialize a SearchResultAnswer object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatefulMessageResponse': + """Initialize a StatefulMessageResponse object from a json dictionary.""" args = {} - if (text := _dict.get('text')) is not None: - args['text'] = text + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) else: raise ValueError( - 'Required property \'text\' not present in SearchResultAnswer JSON' + 'Required property \'output\' not present in StatefulMessageResponse JSON' ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id else: raise ValueError( - 'Required property \'confidence\' not present in SearchResultAnswer JSON' + 'Required property \'user_id\' not present in StatefulMessageResponse JSON' ) + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultAnswer object from a json dictionary.""" + """Initialize a StatefulMessageResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() return _dict def _to_dict(self): @@ -8661,194 +13862,158 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultAnswer object.""" + """Return a `str` version of this StatefulMessageResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultAnswer') -> bool: + def __eq__(self, other: 'StatefulMessageResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResultAnswer') -> bool: + def __ne__(self, other: 'StatefulMessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultHighlight: +class StatelessMessageContext: """ - An object containing segments of text from search results with query-matching text - highlighted using HTML `` tags. + StatelessMessageContext. - :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 taken - from title text in the search results, with query-matching substrings - highlighted. - :param List[str] url: (optional) An array of strings containing segments taken - from URLs in the search results, with query-matching substrings highlighted. + :param StatelessMessageContextGlobal global_: (optional) Session context data + that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - # The set of defined properties for the class - _properties = frozenset(['body', 'title', 'url']) - def __init__( self, *, - body: Optional[List[str]] = None, - title: Optional[List[str]] = None, - url: Optional[List[str]] = None, - **kwargs, + global_: Optional['StatelessMessageContextGlobal'] = None, + skills: Optional['StatelessMessageContextSkills'] = None, + integrations: Optional[dict] = None, ) -> None: """ - Initialize a SearchResultHighlight object. + Initialize a StatelessMessageContext object. - :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 - taken from title text in the search results, with query-matching substrings - highlighted. - :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. + :param StatelessMessageContextGlobal global_: (optional) Session context + data that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data + specific to particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - self.body = body - self.title = title - self.url = url - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.global_ = global_ + self.skills = skills + self.integrations = integrations @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': - """Initialize a SearchResultHighlight object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContext': + """Initialize a StatelessMessageContext object from a json dictionary.""" args = {} - if (body := _dict.get('body')) is not None: - args['body'] = body - if (title := _dict.get('title')) is not None: - args['title'] = title - if (url := _dict.get('url')) is not None: - args['url'] = url - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if (global_ := _dict.get('global')) is not None: + args['global_'] = StatelessMessageContextGlobal.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = StatelessMessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultHighlight object from a json dictionary.""" + """Initialize a StatelessMessageContext object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in SearchResultHighlight._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this SearchResultHighlight object.""" + """Return a `str` version of this StatelessMessageContext object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultHighlight') -> bool: + def __eq__(self, other: 'StatelessMessageContext') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResultHighlight') -> bool: + def __ne__(self, other: 'StatelessMessageContext') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultMetadata: +class StatelessMessageContextGlobal: """ - An object containing search result metadata from the Discovery service. + Session context data that is shared by all skills used by the assistant. - :param float confidence: (optional) The confidence score for the given result, - as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. + :param MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. """ def __init__( self, *, - confidence: Optional[float] = None, - score: Optional[float] = None, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, ) -> None: """ - Initialize a SearchResultMetadata object. + Initialize a StatelessMessageContextGlobal object. - :param float confidence: (optional) The confidence score for the given - result, as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher - score indicates a greater match to the query parameters. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. """ - self.confidence = confidence - self.score = score + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': - """Initialize a SearchResultMetadata object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextGlobal': + """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" args = {} - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (score := _dict.get('score')) is not None: - args['score'] = score + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultMetadata object from a json dictionary.""" + """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id return _dict def _to_dict(self): @@ -8856,103 +14021,78 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultMetadata object.""" + """Return a `str` version of this StatelessMessageContextGlobal object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultMetadata') -> bool: + def __eq__(self, other: 'StatelessMessageContextGlobal') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchResultMetadata') -> bool: + def __ne__(self, other: 'StatelessMessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettings: +class StatelessMessageContextSkills: """ - An object describing the search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and are not - included in **Export skills** responses. + Context data specific to particular skills used by the assistant. - :param SearchSettingsDiscovery discovery: Configuration settings for the Watson - Discovery service instance used by the search integration. - :param SearchSettingsMessages messages: The messages included with responses - from the search integration. - :param SearchSettingsSchemaMapping schema_mapping: The mapping between fields in - the Watson Discovery collection and properties in the search response. + :param MessageContextDialogSkill main_skill: (optional) Context variables that + are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. """ def __init__( self, - discovery: 'SearchSettingsDiscovery', - messages: 'SearchSettingsMessages', - schema_mapping: 'SearchSettingsSchemaMapping', + *, + main_skill: Optional['MessageContextDialogSkill'] = None, + actions_skill: Optional[ + 'StatelessMessageContextSkillsActionsSkill'] = None, ) -> None: """ - Initialize a SearchSettings object. + Initialize a StatelessMessageContextSkills object. - :param SearchSettingsDiscovery discovery: Configuration settings for the - Watson Discovery service instance used by the search integration. - :param SearchSettingsMessages messages: The messages included with - responses from the search integration. - :param SearchSettingsSchemaMapping schema_mapping: The mapping between - fields in the Watson Discovery collection and properties in the search - response. + :param MessageContextDialogSkill main_skill: (optional) Context variables + that are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. """ - self.discovery = discovery - self.messages = messages - self.schema_mapping = schema_mapping + self.main_skill = main_skill + self.actions_skill = actions_skill @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettings': - """Initialize a SearchSettings object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextSkills': + """Initialize a StatelessMessageContextSkills object from a json dictionary.""" args = {} - if (discovery := _dict.get('discovery')) is not None: - args['discovery'] = SearchSettingsDiscovery.from_dict(discovery) - else: - raise ValueError( - 'Required property \'discovery\' not present in SearchSettings JSON' - ) - if (messages := _dict.get('messages')) is not None: - args['messages'] = SearchSettingsMessages.from_dict(messages) - else: - raise ValueError( - 'Required property \'messages\' not present in SearchSettings JSON' - ) - if (schema_mapping := _dict.get('schema_mapping')) is not None: - args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( - schema_mapping) - else: - raise ValueError( - 'Required property \'schema_mapping\' not present in SearchSettings JSON' - ) + if (main_skill := _dict.get('main skill')) is not None: + args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) + if (actions_skill := _dict.get('actions skill')) is not None: + args[ + 'actions_skill'] = StatelessMessageContextSkillsActionsSkill.from_dict( + actions_skill) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettings object from a json dictionary.""" + """Initialize a StatelessMessageContextSkills object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'discovery') and self.discovery is not None: - if isinstance(self.discovery, dict): - _dict['discovery'] = self.discovery - else: - _dict['discovery'] = self.discovery.to_dict() - if hasattr(self, 'messages') and self.messages is not None: - if isinstance(self.messages, dict): - _dict['messages'] = self.messages + if hasattr(self, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill else: - _dict['messages'] = self.messages.to_dict() - if hasattr(self, 'schema_mapping') and self.schema_mapping is not None: - if isinstance(self.schema_mapping, dict): - _dict['schema_mapping'] = self.schema_mapping + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill else: - _dict['schema_mapping'] = self.schema_mapping.to_dict() + _dict['actions skill'] = self.actions_skill.to_dict() return _dict def _to_dict(self): @@ -8960,179 +14100,134 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettings object.""" + """Return a `str` version of this StatelessMessageContextSkills object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettings') -> bool: + def __eq__(self, other: 'StatelessMessageContextSkills') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchSettings') -> bool: + def __ne__(self, other: 'StatelessMessageContextSkills') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsDiscovery: +class StatelessMessageContextSkillsActionsSkill: """ - Configuration settings for the Watson Discovery service instance used by the search - integration. + Context variables that are used by the action skill. - :param str instance_id: The ID for the Watson Discovery service instance. - :param str project_id: The ID for the Watson Discovery project. - :param str url: The URL for the Watson Discovery service instance. - :param int max_primary_results: (optional) The maximum number of primary results - to include in the response. - :param int max_total_results: (optional) The maximum total number of primary and - additional results to include in the response. - :param float confidence_threshold: (optional) The minimum confidence threshold - for included results. Any results with a confidence below this threshold will be - discarded. - :param bool highlight: (optional) Whether to include the most relevant passages - of text in the **highlight** property of each result. - :param bool find_answers: (optional) Whether to use the answer finding feature - to emphasize answers within highlighted passages. This property is ignored if - **highlight**=`false`. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. - :param SearchSettingsDiscoveryAuthentication authentication: Authentication - information for the Watson Discovery service. For more information, see the - [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by + the skill. + :param dict action_variables: (optional) An object containing action variables. + Action variables can be accessed only by steps in the same action, and do not + persist after the action ends. + :param dict skill_variables: (optional) An object containing skill variables. + (In the watsonx Assistant user interface, skill variables are called _session + variables_.) Skill variables can be accessed by any action and persist for the + duration of the session. + :param dict private_action_variables: (optional) An object containing private + action variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. Private variables are + encrypted. + :param dict private_skill_variables: (optional) An object containing private + skill variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action and + persist for the duration of the session. Private variables are encrypted. """ def __init__( self, - instance_id: str, - project_id: str, - url: str, - authentication: 'SearchSettingsDiscoveryAuthentication', *, - max_primary_results: Optional[int] = None, - max_total_results: Optional[int] = None, - confidence_threshold: Optional[float] = None, - highlight: Optional[bool] = None, - find_answers: Optional[bool] = None, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + action_variables: Optional[dict] = None, + skill_variables: Optional[dict] = None, + private_action_variables: Optional[dict] = None, + private_skill_variables: Optional[dict] = None, ) -> None: """ - Initialize a SearchSettingsDiscovery object. + Initialize a StatelessMessageContextSkillsActionsSkill object. - :param str instance_id: The ID for the Watson Discovery service instance. - :param str project_id: The ID for the Watson Discovery project. - :param str url: The URL for the Watson Discovery service instance. - :param SearchSettingsDiscoveryAuthentication authentication: Authentication - information for the Watson Discovery service. For more information, see the - [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. - :param int max_primary_results: (optional) The maximum number of primary - results to include in the response. - :param int max_total_results: (optional) The maximum total number of - primary and additional results to include in the response. - :param float confidence_threshold: (optional) The minimum confidence - threshold for included results. Any results with a confidence below this - threshold will be discarded. - :param bool highlight: (optional) Whether to include the most relevant - passages of text in the **highlight** property of each result. - :param bool find_answers: (optional) Whether to use the answer finding - feature to emphasize answers within highlighted passages. This property is - ignored if **highlight**=`false`. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + :param dict action_variables: (optional) An object containing action + variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. + :param dict skill_variables: (optional) An object containing skill + variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action + and persist for the duration of the session. + :param dict private_action_variables: (optional) An object containing + private action variables. Action variables can be accessed only by steps in + the same action, and do not persist after the action ends. Private + variables are encrypted. + :param dict private_skill_variables: (optional) An object containing + private skill variables. (In the watsonx Assistant user interface, skill + variables are called _session variables_.) Skill variables can be accessed + by any action and persist for the duration of the session. Private + variables are encrypted. """ - self.instance_id = instance_id - self.project_id = project_id - self.url = url - self.max_primary_results = max_primary_results - self.max_total_results = max_total_results - self.confidence_threshold = confidence_threshold - self.highlight = highlight - self.find_answers = find_answers - self.authentication = authentication + self.user_defined = user_defined + self.system = system + self.action_variables = action_variables + self.skill_variables = skill_variables + self.private_action_variables = private_action_variables + self.private_skill_variables = private_skill_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': - """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'StatelessMessageContextSkillsActionsSkill': + """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" args = {} - if (instance_id := _dict.get('instance_id')) is not None: - args['instance_id'] = instance_id - else: - raise ValueError( - 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' - ) - if (project_id := _dict.get('project_id')) is not None: - args['project_id'] = project_id - else: - raise ValueError( - 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' - ) - if (url := _dict.get('url')) is not None: - args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in SearchSettingsDiscovery JSON' - ) - if (max_primary_results := - _dict.get('max_primary_results')) is not None: - args['max_primary_results'] = max_primary_results - if (max_total_results := _dict.get('max_total_results')) is not None: - args['max_total_results'] = max_total_results - if (confidence_threshold := - _dict.get('confidence_threshold')) is not None: - args['confidence_threshold'] = confidence_threshold - if (highlight := _dict.get('highlight')) is not None: - args['highlight'] = highlight - if (find_answers := _dict.get('find_answers')) is not None: - args['find_answers'] = find_answers - if (authentication := _dict.get('authentication')) is not None: - args[ - 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( - authentication) - else: - raise ValueError( - 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' - ) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables + if (skill_variables := _dict.get('skill_variables')) is not None: + args['skill_variables'] = skill_variables + if (private_action_variables := + _dict.get('private_action_variables')) is not None: + args['private_action_variables'] = private_action_variables + if (private_skill_variables := + _dict.get('private_skill_variables')) is not None: + args['private_skill_variables'] = private_skill_variables return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'instance_id') and self.instance_id is not None: - _dict['instance_id'] = self.instance_id - if hasattr(self, 'project_id') and self.project_id is not None: - _dict['project_id'] = self.project_id - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr( - self, - 'max_primary_results') and self.max_primary_results is not None: - _dict['max_primary_results'] = self.max_primary_results - if hasattr(self, - 'max_total_results') and self.max_total_results is not None: - _dict['max_total_results'] = self.max_total_results - if hasattr(self, 'confidence_threshold' - ) and self.confidence_threshold is not None: - _dict['confidence_threshold'] = self.confidence_threshold - if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight - if hasattr(self, 'find_answers') and self.find_answers is not None: - _dict['find_answers'] = self.find_answers - if hasattr(self, 'authentication') and self.authentication is not None: - if isinstance(self.authentication, dict): - _dict['authentication'] = self.authentication + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system else: - _dict['authentication'] = self.authentication.to_dict() + _dict['system'] = self.system.to_dict() + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables + if hasattr(self, + 'skill_variables') and self.skill_variables is not None: + _dict['skill_variables'] = self.skill_variables + if hasattr(self, 'private_action_variables' + ) and self.private_action_variables is not None: + _dict['private_action_variables'] = self.private_action_variables + if hasattr(self, 'private_skill_variables' + ) and self.private_skill_variables is not None: + _dict['private_skill_variables'] = self.private_skill_variables return _dict def _to_dict(self): @@ -9140,74 +14235,177 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsDiscovery object.""" + """Return a `str` version of this StatelessMessageContextSkillsActionsSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsDiscovery') -> bool: + def __eq__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchSettingsDiscovery') -> bool: + def __ne__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsDiscoveryAuthentication: +class StatelessMessageInput: """ - Authentication information for the Watson Discovery service. For more information, see - the [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. + An input object that includes the input text. - :param str basic: (optional) The HTTP basic authentication credentials for - Watson Discovery. Specify your Watson Discovery API key in the format - `apikey:{apikey}`. - :param str bearer: (optional) The authentication bearer token for Watson - Discovery. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param StatelessMessageInputOptions options: (optional) Optional properties that + control how the assistant responds. """ def __init__( self, *, - basic: Optional[str] = None, - bearer: Optional[str] = None, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['StatelessMessageInputOptions'] = None, ) -> None: """ - Initialize a SearchSettingsDiscoveryAuthentication object. + Initialize a StatelessMessageInput object. - :param str basic: (optional) The HTTP basic authentication credentials for - Watson Discovery. Specify your Watson Discovery API key in the format - `apikey:{apikey}`. - :param str bearer: (optional) The authentication bearer token for Watson - Discovery. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param StatelessMessageInputOptions options: (optional) Optional properties + that control how the assistant responds. """ - self.basic = basic - self.bearer = bearer + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': - """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInput': + """Initialize a StatelessMessageInput object from a json dictionary.""" args = {} - if (basic := _dict.get('basic')) is not None: - args['basic'] = basic - if (bearer := _dict.get('bearer')) is not None: - args['bearer'] = bearer + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments + ] + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = StatelessMessageInputOptions.from_dict(options) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + """Initialize a StatelessMessageInput object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'basic') and self.basic is not None: - _dict['basic'] = self.basic - if hasattr(self, 'bearer') and self.bearer is not None: - _dict['bearer'] = self.bearer + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -9215,90 +14413,133 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsDiscoveryAuthentication object.""" + """Return a `str` version of this StatelessMessageInput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: + def __eq__(self, other: 'StatelessMessageInput') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: + def __ne__(self, other: 'StatelessMessageInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + + TEXT = 'text' + SEARCH = 'search' + -class SearchSettingsMessages: +class StatelessMessageInputOptions: """ - The messages included with responses from the search integration. + Optional properties that control how the assistant responds. - :param str success: The message to include in the response to a successful - query. - :param str error: The message to include in the response when the query - encounters an error. - :param str no_result: The message to include in the response when there is no - result from the query. + :param bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the initial + message response signals to the client that the operation may be long running. + With synchronous execution the custom extension is executed and returns the + response in a single message turn. **Note:** **async_callout** defaults to true + for API versions earlier than 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ def __init__( self, - success: str, - error: str, - no_result: str, + *, + restart: Optional[bool] = None, + alternate_intents: Optional[bool] = None, + async_callout: Optional[bool] = None, + spelling: Optional['MessageInputOptionsSpelling'] = None, + debug: Optional[bool] = None, ) -> None: """ - Initialize a SearchSettingsMessages object. + Initialize a StatelessMessageInputOptions object. - :param str success: The message to include in the response to a successful - query. - :param str error: The message to include in the response when the query - encounters an error. - :param str no_result: The message to include in the response when there is - no result from the query. + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the + initial message response signals to the client that the operation may be + long running. With synchronous execution the custom extension is executed + and returns the response in a single message turn. **Note:** + **async_callout** defaults to true for API versions earlier than + 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ - self.success = success - self.error = error - self.no_result = no_result + self.restart = restart + self.alternate_intents = alternate_intents + self.async_callout = async_callout + self.spelling = spelling + self.debug = debug @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': - """Initialize a SearchSettingsMessages object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInputOptions': + """Initialize a StatelessMessageInputOptions object from a json dictionary.""" args = {} - if (success := _dict.get('success')) is not None: - args['success'] = success - else: - raise ValueError( - 'Required property \'success\' not present in SearchSettingsMessages JSON' - ) - if (error := _dict.get('error')) is not None: - args['error'] = error - else: - raise ValueError( - 'Required property \'error\' not present in SearchSettingsMessages JSON' - ) - if (no_result := _dict.get('no_result')) is not None: - args['no_result'] = no_result - else: - raise ValueError( - 'Required property \'no_result\' not present in SearchSettingsMessages JSON' - ) + if (restart := _dict.get('restart')) is not None: + args['restart'] = restart + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (async_callout := _dict.get('async_callout')) is not None: + args['async_callout'] = async_callout + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (debug := _dict.get('debug')) is not None: + args['debug'] = debug return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsMessages object from a json dictionary.""" + """Initialize a StatelessMessageInputOptions object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'success') and self.success is not None: - _dict['success'] = self.success - if hasattr(self, 'error') and self.error is not None: - _dict['error'] = self.error - if hasattr(self, 'no_result') and self.no_result is not None: - _dict['no_result'] = self.no_result + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'async_callout') and self.async_callout is not None: + _dict['async_callout'] = self.async_callout + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug return _dict def _to_dict(self): @@ -9306,91 +14547,137 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsMessages object.""" + """Return a `str` version of this StatelessMessageInputOptions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsMessages') -> bool: + def __eq__(self, other: 'StatelessMessageInputOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchSettingsMessages') -> bool: + def __ne__(self, other: 'StatelessMessageInputOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsSchemaMapping: +class StatelessMessageResponse: """ - The mapping between fields in the Watson Discovery collection and properties in the - search response. + A stateless response from the watsonx Assistant service. - :param str url: The field in the collection to map to the **url** property of - the response. - :param str body: The field in the collection to map to the **body** property in - the response. - :param str title: The field in the collection to map to the **title** property - for the schema. + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param StatelessMessageContext context: Context data for the conversation. You + can use this property to access context variables. The context is not stored by + the assistant; to maintain session state, include the context from the response + in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ def __init__( self, - url: str, - body: str, - title: str, + output: 'MessageOutput', + context: 'StatelessMessageContext', + *, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, + user_id: Optional[str] = None, ) -> None: """ - Initialize a SearchSettingsSchemaMapping object. + Initialize a StatelessMessageResponse object. - :param str url: The field in the collection to map to the **url** property - of the response. - :param str body: The field in the collection to map to the **body** - property in the response. - :param str title: The field in the collection to map to the **title** - property for the schema. + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param StatelessMessageContext context: Context data for the conversation. + You can use this property to access context variables. The context is not + stored by the assistant; to maintain session state, include the context + from the response in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. """ - self.url = url - self.body = body - self.title = title + self.output = output + self.context = context + self.masked_output = masked_output + self.masked_input = masked_input + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': - """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageResponse': + """Initialize a StatelessMessageResponse object from a json dictionary.""" args = {} - if (url := _dict.get('url')) is not None: - args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' - ) - if (body := _dict.get('body')) is not None: - args['body'] = body + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) else: raise ValueError( - 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' + 'Required property \'output\' not present in StatelessMessageResponse JSON' ) - if (title := _dict.get('title')) is not None: - args['title'] = title + if (context := _dict.get('context')) is not None: + args['context'] = StatelessMessageContext.from_dict(context) else: raise ValueError( - 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' + 'Required property \'context\' not present in StatelessMessageResponse JSON' ) + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + """Initialize a StatelessMessageResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -9398,73 +14685,56 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsSchemaMapping object.""" + """Return a `str` version of this StatelessMessageResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsSchemaMapping') -> bool: + def __eq__(self, other: 'StatelessMessageResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SearchSettingsSchemaMapping') -> bool: + def __ne__(self, other: 'StatelessMessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSkillWarning: +class StatusError: """ - A warning describing an error in the search skill configuration. + An object describing an error that occurred during processing of an asynchronous + operation. - :param str code: (optional) The error code. - :param str path: (optional) The location of the error in the search skill - configuration object. - :param str message: (optional) The error message. + :param str message: (optional) The text of the error message. """ def __init__( self, *, - code: Optional[str] = None, - path: Optional[str] = None, message: Optional[str] = None, ) -> None: """ - Initialize a SearchSkillWarning object. + Initialize a StatusError object. - :param str code: (optional) The error code. - :param str path: (optional) The location of the error in the search skill - configuration object. - :param str message: (optional) The error message. + :param str message: (optional) The text of the error message. """ - self.code = code - self.path = path self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': - """Initialize a SearchSkillWarning object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatusError': + """Initialize a StatusError object from a json dictionary.""" args = {} - if (code := _dict.get('code')) is not None: - args['code'] = code - if (path := _dict.get('path')) is not None: - args['path'] = path if (message := _dict.get('message')) is not None: args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSkillWarning object from a json dictionary.""" + """Initialize a StatusError object from 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: - _dict['code'] = self.code - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path if hasattr(self, 'message') and self.message is not None: _dict['message'] = self.message return _dict @@ -9474,300 +14744,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSkillWarning object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SearchSkillWarning') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ - - def __ne__(self, other: 'SearchSkillWarning') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SessionResponse: - """ - SessionResponse. - - :param str session_id: The session ID. - """ - - def __init__( - self, - session_id: str, - ) -> None: - """ - Initialize a SessionResponse object. - - :param str session_id: The session ID. - """ - self.session_id = session_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SessionResponse': - """Initialize a SessionResponse object from a json dictionary.""" - args = {} - if (session_id := _dict.get('session_id')) is not None: - args['session_id'] = session_id - else: - raise ValueError( - 'Required property \'session_id\' not present in SessionResponse JSON' - ) - return cls(**args) - - @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 _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 a `str` version of this StatusError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SessionResponse') -> bool: + def __eq__(self, other: 'StatusError') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SessionResponse') -> bool: + def __ne__(self, other: 'StatusError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Skill: +class TurnEventActionSource: """ - Skill. + TurnEventActionSource. - :param str name: (optional) The name of the skill. This string cannot contain - carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This string - cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param str skill_id: (optional) The skill ID of the skill. - :param str status: (optional) The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param dict dialog_settings: (optional) For internal use only. - :param str assistant_id: (optional) The unique identifier of the assistant the - skill is associated with. - :param str workspace_id: (optional) The unique identifier of the workspace that - contains the skill content. Included only for action and dialog skills. - :param str environment_id: (optional) The unique identifier of the environment - where the skill is defined. For action and dialog skills, this is always the - draft environment. - :param bool valid: (optional) Whether the skill is structurally valid. - :param str next_snapshot_version: (optional) The name that will be given to the - next snapshot that is created for the skill. A snapshot of each versionable - skill is saved for each new release of an assistant. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and - are not included in **Export skills** responses. - :param List[SearchSkillWarning] warnings: (optional) An array of warnings - describing errors with the search skill configuration. Included only for search - skills. - :param str language: The language of the skill. - :param str type: The type of skill. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing of + the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog node. """ def __init__( self, - language: str, - type: str, *, - name: Optional[str] = None, - description: Optional[str] = None, - workspace: Optional[dict] = None, - skill_id: Optional[str] = None, - status: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, - status_description: Optional[str] = None, - dialog_settings: Optional[dict] = None, - assistant_id: Optional[str] = None, - workspace_id: Optional[str] = None, - environment_id: Optional[str] = None, - valid: Optional[bool] = None, - next_snapshot_version: Optional[str] = None, - search_settings: Optional['SearchSettings'] = None, - warnings: Optional[List['SearchSkillWarning']] = None, + type: Optional[str] = None, + action: Optional[str] = None, + action_title: Optional[str] = None, + condition: Optional[str] = None, ) -> None: """ - Initialize a Skill object. - - :param str language: The language of the skill. - :param str type: The type of skill. - :param str name: (optional) The name of the skill. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This - string cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param dict dialog_settings: (optional) For internal use only. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, - and are not included in **Export skills** responses. - """ - self.name = name - self.description = description - self.workspace = workspace - self.skill_id = skill_id - self.status = status - self.status_errors = status_errors - self.status_description = status_description - self.dialog_settings = dialog_settings - self.assistant_id = assistant_id - self.workspace_id = workspace_id - self.environment_id = environment_id - self.valid = valid - self.next_snapshot_version = next_snapshot_version - self.search_settings = search_settings - self.warnings = warnings - self.language = language + Initialize a TurnEventActionSource object. + + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing + of the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog + node. + """ self.type = type + self.action = action + self.action_title = action_title + self.condition = condition @classmethod - def from_dict(cls, _dict: Dict) -> 'Skill': - """Initialize a Skill object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventActionSource': + """Initialize a TurnEventActionSource object from a json dictionary.""" args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (workspace := _dict.get('workspace')) is not None: - args['workspace'] = workspace - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (dialog_settings := _dict.get('dialog_settings')) is not None: - args['dialog_settings'] = dialog_settings - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (workspace_id := _dict.get('workspace_id')) is not None: - args['workspace_id'] = workspace_id - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (valid := _dict.get('valid')) is not None: - args['valid'] = valid - if (next_snapshot_version := - _dict.get('next_snapshot_version')) is not None: - args['next_snapshot_version'] = next_snapshot_version - if (search_settings := _dict.get('search_settings')) is not None: - args['search_settings'] = SearchSettings.from_dict(search_settings) - if (warnings := _dict.get('warnings')) is not None: - args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in warnings - ] - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in Skill JSON') if (type := _dict.get('type')) is not None: args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in Skill JSON') + if (action := _dict.get('action')) is not None: + args['action'] = action + if (action_title := _dict.get('action_title')) is not None: + args['action_title'] = action_title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Skill object from a json dictionary.""" + """Initialize a TurnEventActionSource object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'workspace') and self.workspace is not None: - _dict['workspace'] = self.workspace - if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: - _dict['skill_id'] = getattr(self, 'skill_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, - 'dialog_settings') and self.dialog_settings is not None: - _dict['dialog_settings'] = self.dialog_settings - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'workspace_id') and getattr( - self, 'workspace_id') is not None: - _dict['workspace_id'] = getattr(self, 'workspace_id') - if hasattr(self, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'valid') and getattr(self, 'valid') is not None: - _dict['valid'] = getattr(self, 'valid') - if hasattr(self, 'next_snapshot_version') and getattr( - self, 'next_snapshot_version') is not None: - _dict['next_snapshot_version'] = getattr(self, - 'next_snapshot_version') - if hasattr(self, - 'search_settings') and self.search_settings is not None: - if isinstance(self.search_settings, dict): - _dict['search_settings'] = self.search_settings - else: - _dict['search_settings'] = self.search_settings.to_dict() - if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: - warnings_list = [] - for v in getattr(self, 'warnings'): - if isinstance(v, dict): - warnings_list.append(v) - else: - warnings_list.append(v.to_dict()) - _dict['warnings'] = warnings_list - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'action_title') and self.action_title is not None: + _dict['action_title'] = self.action_title + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition return _dict def _to_dict(self): @@ -9775,267 +14829,112 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Skill object.""" + """Return a `str` version of this TurnEventActionSource object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Skill') -> bool: + def __eq__(self, other: 'TurnEventActionSource') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'Skill') -> bool: + def __ne__(self, other: 'TurnEventActionSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - """ - - AVAILABLE = 'Available' - FAILED = 'Failed' - NON_EXISTENT = 'Non Existent' - PROCESSING = 'Processing' - TRAINING = 'Training' - UNAVAILABLE = 'Unavailable' - class TypeEnum(str, Enum): """ - The type of skill. + The type of turn event. """ ACTION = 'action' - DIALOG = 'dialog' - SEARCH = 'search' -class SkillImport: +class TurnEventCalloutCallout: """ - SkillImport. + TurnEventCalloutCallout. - :param str name: (optional) The name of the skill. This string cannot contain - carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This string - cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param str skill_id: (optional) The skill ID of the skill. - :param str status: (optional) The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param dict dialog_settings: (optional) For internal use only. - :param str assistant_id: (optional) The unique identifier of the assistant the - skill is associated with. - :param str workspace_id: (optional) The unique identifier of the workspace that - contains the skill content. Included only for action and dialog skills. - :param str environment_id: (optional) The unique identifier of the environment - where the skill is defined. For action and dialog skills, this is always the - draft environment. - :param bool valid: (optional) Whether the skill is structurally valid. - :param str next_snapshot_version: (optional) The name that will be given to the - next snapshot that is created for the skill. A snapshot of each versionable - skill is saved for each new release of an assistant. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and - are not included in **Export skills** responses. - :param List[SearchSkillWarning] warnings: (optional) An array of warnings - describing errors with the search skill configuration. Included only for search - skills. - :param str language: The language of the skill. - :param str type: The type of skill. + :param str type: (optional) The type of callout. Currently, the only supported + value is `integration_interaction` (for calls to extensions). + :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. + :param TurnEventCalloutCalloutRequest request: (optional) The request object + executed to the external server specified by the extension. + :param TurnEventCalloutCalloutResponse response: (optional) The response object + received by the external server made by the extension. """ def __init__( self, - language: str, - type: str, *, - name: Optional[str] = None, - description: Optional[str] = None, - workspace: Optional[dict] = None, - skill_id: Optional[str] = None, - status: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, - status_description: Optional[str] = None, - dialog_settings: Optional[dict] = None, - assistant_id: Optional[str] = None, - workspace_id: Optional[str] = None, - environment_id: Optional[str] = None, - valid: Optional[bool] = None, - next_snapshot_version: Optional[str] = None, - search_settings: Optional['SearchSettings'] = None, - warnings: Optional[List['SearchSkillWarning']] = None, - ) -> None: - """ - Initialize a SkillImport object. - - :param str language: The language of the skill. - :param str type: The type of skill. - :param str name: (optional) The name of the skill. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This - string cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param dict dialog_settings: (optional) For internal use only. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, - and are not included in **Export skills** responses. + type: Optional[str] = None, + internal: Optional[dict] = None, + result_variable: Optional[str] = None, + request: Optional['TurnEventCalloutCalloutRequest'] = None, + response: Optional['TurnEventCalloutCalloutResponse'] = None, + ) -> None: + """ + Initialize a TurnEventCalloutCallout object. + + :param str type: (optional) The type of callout. Currently, the only + supported value is `integration_interaction` (for calls to extensions). + :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. + :param TurnEventCalloutCalloutRequest request: (optional) The request + object executed to the external server specified by the extension. + :param TurnEventCalloutCalloutResponse response: (optional) The response + object received by the external server made by the extension. """ - self.name = name - self.description = description - self.workspace = workspace - self.skill_id = skill_id - self.status = status - self.status_errors = status_errors - self.status_description = status_description - self.dialog_settings = dialog_settings - self.assistant_id = assistant_id - self.workspace_id = workspace_id - self.environment_id = environment_id - self.valid = valid - self.next_snapshot_version = next_snapshot_version - self.search_settings = search_settings - self.warnings = warnings - self.language = language self.type = type + self.internal = internal + self.result_variable = result_variable + self.request = request + self.response = response @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillImport': - """Initialize a SkillImport object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': + """Initialize a TurnEventCalloutCallout object from a json dictionary.""" args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (workspace := _dict.get('workspace')) is not None: - args['workspace'] = workspace - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (dialog_settings := _dict.get('dialog_settings')) is not None: - args['dialog_settings'] = dialog_settings - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (workspace_id := _dict.get('workspace_id')) is not None: - args['workspace_id'] = workspace_id - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (valid := _dict.get('valid')) is not None: - args['valid'] = valid - if (next_snapshot_version := - _dict.get('next_snapshot_version')) is not None: - args['next_snapshot_version'] = next_snapshot_version - if (search_settings := _dict.get('search_settings')) is not None: - args['search_settings'] = SearchSettings.from_dict(search_settings) - if (warnings := _dict.get('warnings')) is not None: - args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in warnings - ] - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in SkillImport JSON' - ) if (type := _dict.get('type')) is not None: args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in SkillImport JSON') + if (internal := _dict.get('internal')) is not None: + args['internal'] = internal + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable + if (request := _dict.get('request')) is not None: + args['request'] = TurnEventCalloutCalloutRequest.from_dict(request) + if (response := _dict.get('response')) is not None: + args['response'] = TurnEventCalloutCalloutResponse.from_dict( + response) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillImport object from a json dictionary.""" + """Initialize a TurnEventCalloutCallout object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'workspace') and self.workspace is not None: - _dict['workspace'] = self.workspace - if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: - _dict['skill_id'] = getattr(self, 'skill_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, - 'dialog_settings') and self.dialog_settings is not None: - _dict['dialog_settings'] = self.dialog_settings - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'workspace_id') and getattr( - self, 'workspace_id') is not None: - _dict['workspace_id'] = getattr(self, 'workspace_id') - if hasattr(self, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'valid') and getattr(self, 'valid') is not None: - _dict['valid'] = getattr(self, 'valid') - if hasattr(self, 'next_snapshot_version') and getattr( - self, 'next_snapshot_version') is not None: - _dict['next_snapshot_version'] = getattr(self, - 'next_snapshot_version') - if hasattr(self, - 'search_settings') and self.search_settings is not None: - if isinstance(self.search_settings, dict): - _dict['search_settings'] = self.search_settings - else: - _dict['search_settings'] = self.search_settings.to_dict() - if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: - warnings_list = [] - for v in getattr(self, 'warnings'): - if isinstance(v, dict): - warnings_list.append(v) - else: - warnings_list.append(v.to_dict()) - _dict['warnings'] = warnings_list - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type + if hasattr(self, 'internal') and self.internal is not None: + _dict['internal'] = self.internal + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable + if hasattr(self, 'request') and self.request is not None: + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() return _dict def _to_dict(self): @@ -10043,122 +14942,112 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillImport object.""" + """Return a `str` version of this TurnEventCalloutCallout object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillImport') -> bool: + def __eq__(self, other: 'TurnEventCalloutCallout') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SkillImport') -> bool: + def __ne__(self, other: 'TurnEventCalloutCallout') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - """ - - AVAILABLE = 'Available' - FAILED = 'Failed' - NON_EXISTENT = 'Non Existent' - PROCESSING = 'Processing' - TRAINING = 'Training' - UNAVAILABLE = 'Unavailable' - class TypeEnum(str, Enum): """ - The type of skill. + The type of callout. Currently, the only supported value is + `integration_interaction` (for calls to extensions). """ - ACTION = 'action' - DIALOG = 'dialog' + INTEGRATION_INTERACTION = 'integration_interaction' -class SkillsAsyncRequestStatus: +class TurnEventCalloutCalloutRequest: """ - SkillsAsyncRequestStatus. - - :param str assistant_id: (optional) The assistant ID of the assistant. - :param str status: (optional) The current status of the asynchronous operation: - - `Available`: An asynchronous export is available. - - `Completed`: An asynchronous import operation has completed successfully. - - `Failed`: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - `Processing`: An asynchronous operation has not yet completed. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. + TurnEventCalloutCalloutRequest. + + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to the URL + of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server or an + object. In cases like timeouts or connections errors, it will contain details of + why the callout to the external server failed. """ def __init__( self, *, - assistant_id: Optional[str] = None, - status: Optional[str] = None, - status_description: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, + method: Optional[str] = None, + url: Optional[str] = None, + path: Optional[str] = None, + query_parameters: Optional[str] = None, + headers_: Optional[dict] = None, + body: Optional[dict] = None, ) -> None: """ - Initialize a SkillsAsyncRequestStatus object. + Initialize a TurnEventCalloutCalloutRequest object. + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to + the URL of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server + or an object. In cases like timeouts or connections errors, it will contain + details of why the callout to the external server failed. """ - self.assistant_id = assistant_id - self.status = status - self.status_description = status_description - self.status_errors = status_errors + self.method = method + self.url = url + self.path = path + self.query_parameters = query_parameters + self.headers_ = headers_ + self.body = body @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': - """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCalloutRequest': + """Initialize a TurnEventCalloutCalloutRequest object from a json dictionary.""" args = {} - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] + if (method := _dict.get('method')) is not None: + args['method'] = method + if (url := _dict.get('url')) is not None: + args['url'] = url + if (path := _dict.get('path')) is not None: + args['path'] = path + if (query_parameters := _dict.get('query_parameters')) is not None: + args['query_parameters'] = query_parameters + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = headers_ + if (body := _dict.get('body')) is not None: + args['body'] = body return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + """Initialize a TurnEventCalloutCalloutRequest object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'method') and self.method is not None: + _dict['method'] = self.method + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, + 'query_parameters') and self.query_parameters is not None: + _dict['query_parameters'] = self.query_parameters + if hasattr(self, 'headers_') and self.headers_ is not None: + _dict['headers'] = self.headers_ + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body return _dict def _to_dict(self): @@ -10166,105 +15055,88 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillsAsyncRequestStatus object.""" + """Return a `str` version of this TurnEventCalloutCalloutRequest object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillsAsyncRequestStatus') -> bool: + def __eq__(self, other: 'TurnEventCalloutCalloutRequest') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SkillsAsyncRequestStatus') -> bool: + def __ne__(self, other: 'TurnEventCalloutCalloutRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): + class MethodEnum(str, Enum): """ - The current status of the asynchronous operation: - - `Available`: An asynchronous export is available. - - `Completed`: An asynchronous import operation has completed successfully. - - `Failed`: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - `Processing`: An asynchronous operation has not yet completed. + The REST method of the request. """ - AVAILABLE = 'Available' - COMPLETED = 'Completed' - FAILED = 'Failed' - PROCESSING = 'Processing' + GET = 'get' + POST = 'post' + PUT = 'put' + DELETE = 'delete' + PATCH = 'patch' -class SkillsExport: +class TurnEventCalloutCalloutResponse: """ - SkillsExport. + TurnEventCalloutCalloutResponse. - :param List[Skill] assistant_skills: An array of objects describing the skills - for the assistant. Included in responses only if **status**=`Available`. - :param AssistantState assistant_state: Status information about the skills for - the assistant. Included in responses only if **status**=`Available`. + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. + :param dict last_event: (optional) The response from the last chunk received + from the response stream. """ def __init__( self, - assistant_skills: List['Skill'], - assistant_state: 'AssistantState', + *, + body: Optional[str] = None, + status_code: Optional[int] = None, + last_event: Optional[dict] = None, ) -> None: """ - Initialize a SkillsExport object. + Initialize a TurnEventCalloutCalloutResponse object. - :param List[Skill] assistant_skills: An array of objects describing the - skills for the assistant. Included in responses only if - **status**=`Available`. - :param AssistantState assistant_state: Status information about the skills - for the assistant. Included in responses only if **status**=`Available`. + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. + :param dict last_event: (optional) The response from the last chunk + received from the response stream. """ - self.assistant_skills = assistant_skills - self.assistant_state = assistant_state + self.body = body + self.status_code = status_code + self.last_event = last_event @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillsExport': - """Initialize a SkillsExport object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCalloutResponse': + """Initialize a TurnEventCalloutCalloutResponse object from a json dictionary.""" args = {} - if (assistant_skills := _dict.get('assistant_skills')) is not None: - args['assistant_skills'] = [ - Skill.from_dict(v) for v in assistant_skills - ] - else: - raise ValueError( - 'Required property \'assistant_skills\' not present in SkillsExport JSON' - ) - if (assistant_state := _dict.get('assistant_state')) is not None: - args['assistant_state'] = AssistantState.from_dict(assistant_state) - else: - raise ValueError( - 'Required property \'assistant_state\' not present in SkillsExport JSON' - ) + if (body := _dict.get('body')) is not None: + args['body'] = body + if (status_code := _dict.get('status_code')) is not None: + args['status_code'] = status_code + if (last_event := _dict.get('last_event')) is not None: + args['last_event'] = last_event return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillsExport object from a json dictionary.""" + """Initialize a TurnEventCalloutCalloutResponse object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, - 'assistant_skills') and self.assistant_skills is not None: - assistant_skills_list = [] - for v in self.assistant_skills: - if isinstance(v, dict): - assistant_skills_list.append(v) - else: - assistant_skills_list.append(v.to_dict()) - _dict['assistant_skills'] = assistant_skills_list - if hasattr(self, - 'assistant_state') and self.assistant_state is not None: - if isinstance(self.assistant_state, dict): - _dict['assistant_state'] = self.assistant_state - else: - _dict['assistant_state'] = self.assistant_state.to_dict() + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'status_code') and self.status_code is not None: + _dict['status_code'] = self.status_code + if hasattr(self, 'last_event') and self.last_event is not None: + _dict['last_event'] = self.last_event return _dict def _to_dict(self): @@ -10272,141 +15144,59 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillsExport object.""" + """Return a `str` version of this TurnEventCalloutCalloutResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillsExport') -> bool: + def __eq__(self, other: 'TurnEventCalloutCalloutResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'SkillsExport') -> bool: + def __ne__(self, other: 'TurnEventCalloutCalloutResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatefulMessageResponse: +class TurnEventCalloutError: """ - A response from the watsonx Assistant service. + TurnEventCalloutError. - :param MessageOutput output: Assistant output to be rendered or processed by the - client. - :param MessageContext context: (optional) Context data for the conversation. You - can use this property to access context variables. The context is stored by the - assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :param str user_id: A string value that identifies the user who is interacting - with the assistant. The client must provide a unique identifier for each - individual end user who accesses the application. For user-based plans, this - user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. - :param MessageOutput masked_output: (optional) Assistant output to be rendered - or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes the - input text. All private data is masked or removed. + :param str message: (optional) Any error message returned by a failed call to an + external service. """ def __init__( self, - output: 'MessageOutput', - user_id: str, *, - context: Optional['MessageContext'] = None, - masked_output: Optional['MessageOutput'] = None, - masked_input: Optional['MessageInput'] = None, + message: Optional[str] = None, ) -> None: """ - Initialize a StatefulMessageResponse object. + Initialize a TurnEventCalloutError object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param str user_id: A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier - for each individual end user who accesses the application. For user-based - plans, this user ID is used to identify unique users for billing purposes. - This string cannot contain carriage return, newline, or tab characters. If - no value is specified in the input, **user_id** is automatically set to the - value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to access context variables. The - context is stored by the assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :param MessageOutput masked_output: (optional) Assistant output to be - rendered or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes - the input text. All private data is masked or removed. + :param str message: (optional) Any error message returned by a failed call + to an external service. """ - self.output = output - self.context = context - self.user_id = user_id - self.masked_output = masked_output - self.masked_input = masked_input + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'StatefulMessageResponse': - """Initialize a StatefulMessageResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutError': + """Initialize a TurnEventCalloutError object from a json dictionary.""" args = {} - if (output := _dict.get('output')) is not None: - args['output'] = MessageOutput.from_dict(output) - else: - raise ValueError( - 'Required property \'output\' not present in StatefulMessageResponse JSON' - ) - if (context := _dict.get('context')) is not None: - args['context'] = MessageContext.from_dict(context) - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id - else: - raise ValueError( - 'Required property \'user_id\' not present in StatefulMessageResponse JSON' - ) - if (masked_output := _dict.get('masked_output')) is not None: - args['masked_output'] = MessageOutput.from_dict(masked_output) - if (masked_input := _dict.get('masked_input')) is not None: - args['masked_input'] = MessageInput.from_dict(masked_input) + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatefulMessageResponse object from a json dictionary.""" + """Initialize a TurnEventCalloutError object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - if hasattr(self, 'masked_output') and self.masked_output is not None: - if isinstance(self.masked_output, dict): - _dict['masked_output'] = self.masked_output - else: - _dict['masked_output'] = self.masked_output.to_dict() - if hasattr(self, 'masked_input') and self.masked_input is not None: - if isinstance(self.masked_input, dict): - _dict['masked_input'] = self.masked_input - else: - _dict['masked_input'] = self.masked_input.to_dict() + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -10414,87 +15204,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatefulMessageResponse object.""" + """Return a `str` version of this TurnEventCalloutError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatefulMessageResponse') -> bool: + def __eq__(self, other: 'TurnEventCalloutError') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'StatefulMessageResponse') -> bool: + def __ne__(self, other: 'TurnEventCalloutError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageContext: +class TurnEventNodeSource: """ - StatelessMessageContext. + TurnEventNodeSource. - :param StatelessMessageContextGlobal global_: (optional) Session context data - that is shared by all skills used by the assistant. - :param StatelessMessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str condition: (optional) The condition that triggered the dialog node. """ def __init__( self, *, - global_: Optional['StatelessMessageContextGlobal'] = None, - skills: Optional['StatelessMessageContextSkills'] = None, - integrations: Optional[dict] = None, + type: Optional[str] = None, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + condition: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageContext object. + Initialize a TurnEventNodeSource object. - :param StatelessMessageContextGlobal global_: (optional) Session context - data that is shared by all skills used by the assistant. - :param StatelessMessageContextSkills skills: (optional) Context data - specific to particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that - is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str condition: (optional) The condition that triggered the dialog + node. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.type = type + self.dialog_node = dialog_node + self.title = title + self.condition = condition @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageContext': - """Initialize a StatelessMessageContext object from a json dictionary.""" - args = {} - if (global_ := _dict.get('global')) is not None: - args['global_'] = StatelessMessageContextGlobal.from_dict(global_) - if (skills := _dict.get('skills')) is not None: - args['skills'] = StatelessMessageContextSkills.from_dict(skills) - if (integrations := _dict.get('integrations')) is not None: - args['integrations'] = integrations + def from_dict(cls, _dict: Dict) -> 'TurnEventNodeSource': + """Initialize a TurnEventNodeSource object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageContext object from a json dictionary.""" + """Initialize a TurnEventNodeSource object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'global_') and self.global_ is not None: - if isinstance(self.global_, dict): - _dict['global'] = self.global_ - else: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - if isinstance(self.skills, dict): - _dict['skills'] = self.skills - else: - _dict['skills'] = self.skills.to_dict() - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition return _dict def _to_dict(self): @@ -10502,70 +15289,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContext object.""" + """Return a `str` version of this TurnEventNodeSource object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageContext') -> bool: + def __eq__(self, other: 'TurnEventNodeSource') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'StatelessMessageContext') -> bool: + def __ne__(self, other: 'TurnEventNodeSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of turn event. + """ + + DIALOG_NODE = 'dialog_node' + -class StatelessMessageContextGlobal: +class TurnEventSearchError: """ - Session context data that is shared by all skills used by the assistant. + TurnEventSearchError. - :param MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param str message: (optional) Any error message returned by a failed call to a + search skill. """ def __init__( self, *, - system: Optional['MessageContextGlobalSystem'] = None, - session_id: Optional[str] = None, + message: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageContextGlobal object. + Initialize a TurnEventSearchError object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param str message: (optional) Any error message returned by a failed call + to a search skill. """ - self.system = system - self.session_id = session_id + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextGlobal': - """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError': + """Initialize a TurnEventSearchError object from a json dictionary.""" args = {} - if (system := _dict.get('system')) is not None: - args['system'] = MessageContextGlobalSystem.from_dict(system) - if (session_id := _dict.get('session_id')) is not None: - args['session_id'] = session_id + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" + """Initialize a TurnEventSearchError object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system - else: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -10573,78 +15356,65 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContextGlobal object.""" + """Return a `str` version of this TurnEventSearchError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageContextGlobal') -> bool: + def __eq__(self, other: 'TurnEventSearchError') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'StatelessMessageContextGlobal') -> bool: + def __ne__(self, other: 'TurnEventSearchError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageContextSkills: +class UpdateEnvironmentOrchestration: """ - Context data specific to particular skills used by the assistant. + The search skill orchestration settings for the environment. - :param MessageContextDialogSkill main_skill: (optional) Context variables that - are used by the dialog skill. - :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) - Context variables that are used by the action skill. + :param bool search_skill_fallback: (optional) Whether to fall back to a search + skill when responding to messages that do not match any intent or action defined + in dialog or action skills. (If no search skill is configured for the + environment, this property is ignored.). """ def __init__( self, *, - main_skill: Optional['MessageContextDialogSkill'] = None, - actions_skill: Optional[ - 'StatelessMessageContextSkillsActionsSkill'] = None, + search_skill_fallback: Optional[bool] = None, ) -> None: """ - Initialize a StatelessMessageContextSkills object. + Initialize a UpdateEnvironmentOrchestration object. - :param MessageContextDialogSkill main_skill: (optional) Context variables - that are used by the dialog skill. - :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) - Context variables that are used by the action skill. + :param bool search_skill_fallback: (optional) Whether to fall back to a + search skill when responding to messages that do not match any intent or + action defined in dialog or action skills. (If no search skill is + configured for the environment, this property is ignored.). """ - self.main_skill = main_skill - self.actions_skill = actions_skill + self.search_skill_fallback = search_skill_fallback @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextSkills': - """Initialize a StatelessMessageContextSkills object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'UpdateEnvironmentOrchestration': + """Initialize a UpdateEnvironmentOrchestration object from a json dictionary.""" args = {} - if (main_skill := _dict.get('main skill')) is not None: - args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) - if (actions_skill := _dict.get('actions skill')) is not None: - args[ - 'actions_skill'] = StatelessMessageContextSkillsActionsSkill.from_dict( - actions_skill) + if (search_skill_fallback := + _dict.get('search_skill_fallback')) is not None: + args['search_skill_fallback'] = search_skill_fallback return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageContextSkills object from a json dictionary.""" + """Initialize a UpdateEnvironmentOrchestration object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'main_skill') and self.main_skill is not None: - if isinstance(self.main_skill, dict): - _dict['main skill'] = self.main_skill - else: - _dict['main skill'] = self.main_skill.to_dict() - if hasattr(self, 'actions_skill') and self.actions_skill is not None: - if isinstance(self.actions_skill, dict): - _dict['actions skill'] = self.actions_skill - else: - _dict['actions skill'] = self.actions_skill.to_dict() + if hasattr(self, 'search_skill_fallback' + ) and self.search_skill_fallback is not None: + _dict['search_skill_fallback'] = self.search_skill_fallback return _dict def _to_dict(self): @@ -10652,134 +15422,57 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContextSkills object.""" + """Return a `str` version of this UpdateEnvironmentOrchestration object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageContextSkills') -> bool: + def __eq__(self, other: 'UpdateEnvironmentOrchestration') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'StatelessMessageContextSkills') -> bool: + def __ne__(self, other: 'UpdateEnvironmentOrchestration') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageContextSkillsActionsSkill: +class UpdateEnvironmentReleaseReference: """ - Context variables that are used by the action skill. + An object describing the release that is currently deployed in the environment. - :param dict user_defined: (optional) An object containing any arbitrary - variables that can be read and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data used by - the skill. - :param dict action_variables: (optional) An object containing action variables. - Action variables can be accessed only by steps in the same action, and do not - persist after the action ends. - :param dict skill_variables: (optional) An object containing skill variables. - (In the watsonx Assistant user interface, skill variables are called _session - variables_.) Skill variables can be accessed by any action and persist for the - duration of the session. - :param dict private_action_variables: (optional) An object containing private - action variables. Action variables can be accessed only by steps in the same - action, and do not persist after the action ends. Private variables are - encrypted. - :param dict private_skill_variables: (optional) An object containing private - skill variables. (In the watsonx Assistant user interface, skill variables are - called _session variables_.) Skill variables can be accessed by any action and - persist for the duration of the session. Private variables are encrypted. + :param str release: (optional) The name of the deployed release. """ def __init__( self, *, - user_defined: Optional[dict] = None, - system: Optional['MessageContextSkillSystem'] = None, - action_variables: Optional[dict] = None, - skill_variables: Optional[dict] = None, - private_action_variables: Optional[dict] = None, - private_skill_variables: Optional[dict] = None, + release: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageContextSkillsActionsSkill object. + Initialize a UpdateEnvironmentReleaseReference object. - :param dict user_defined: (optional) An object containing any arbitrary - variables that can be read and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data - used by the skill. - :param dict action_variables: (optional) An object containing action - variables. Action variables can be accessed only by steps in the same - action, and do not persist after the action ends. - :param dict skill_variables: (optional) An object containing skill - variables. (In the watsonx Assistant user interface, skill variables are - called _session variables_.) Skill variables can be accessed by any action - and persist for the duration of the session. - :param dict private_action_variables: (optional) An object containing - private action variables. Action variables can be accessed only by steps in - the same action, and do not persist after the action ends. Private - variables are encrypted. - :param dict private_skill_variables: (optional) An object containing - private skill variables. (In the watsonx Assistant user interface, skill - variables are called _session variables_.) Skill variables can be accessed - by any action and persist for the duration of the session. Private - variables are encrypted. + :param str release: (optional) The name of the deployed release. """ - self.user_defined = user_defined - self.system = system - self.action_variables = action_variables - self.skill_variables = skill_variables - self.private_action_variables = private_action_variables - self.private_skill_variables = private_skill_variables - - @classmethod - def from_dict(cls, - _dict: Dict) -> 'StatelessMessageContextSkillsActionsSkill': - """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" - args = {} - if (user_defined := _dict.get('user_defined')) is not None: - args['user_defined'] = user_defined - if (system := _dict.get('system')) is not None: - args['system'] = MessageContextSkillSystem.from_dict(system) - if (action_variables := _dict.get('action_variables')) is not None: - args['action_variables'] = action_variables - if (skill_variables := _dict.get('skill_variables')) is not None: - args['skill_variables'] = skill_variables - if (private_action_variables := - _dict.get('private_action_variables')) is not None: - args['private_action_variables'] = private_action_variables - if (private_skill_variables := - _dict.get('private_skill_variables')) is not None: - args['private_skill_variables'] = private_skill_variables - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system - else: - _dict['system'] = self.system.to_dict() - if hasattr(self, - 'action_variables') and self.action_variables is not None: - _dict['action_variables'] = self.action_variables - if hasattr(self, - 'skill_variables') and self.skill_variables is not None: - _dict['skill_variables'] = self.skill_variables - if hasattr(self, 'private_action_variables' - ) and self.private_action_variables is not None: - _dict['private_action_variables'] = self.private_action_variables - if hasattr(self, 'private_skill_variables' - ) and self.private_skill_variables is not None: - _dict['private_skill_variables'] = self.private_skill_variables + self.release = release + + @classmethod + def from_dict(cls, _dict: Dict) -> 'UpdateEnvironmentReleaseReference': + """Initialize a UpdateEnvironmentReleaseReference object from a json dictionary.""" + args = {} + if (release := _dict.get('release')) is not None: + args['release'] = release + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a UpdateEnvironmentReleaseReference object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'release') and self.release is not None: + _dict['release'] = self.release return _dict def _to_dict(self): @@ -10787,177 +15480,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContextSkillsActionsSkill object.""" + """Return a `str` version of this UpdateEnvironmentReleaseReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'StatelessMessageContextSkillsActionsSkill') -> bool: + def __eq__(self, other: 'UpdateEnvironmentReleaseReference') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, - other: 'StatelessMessageContextSkillsActionsSkill') -> bool: + def __ne__(self, other: 'UpdateEnvironmentReleaseReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageInput: +class CompleteItem(RuntimeResponseGeneric): """ - An input object that includes the input text. + CompleteItem. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating - the user input. Include intents from the previous response to continue using - those intents rather than trying to recognize intents in the new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the Segment - extension. - :param StatelessMessageInputOptions options: (optional) Optional properties that - control how the assistant responds. + :param Metadata streaming_metadata: """ def __init__( self, - *, - message_type: Optional[str] = None, - text: Optional[str] = None, - intents: Optional[List['RuntimeIntent']] = None, - entities: Optional[List['RuntimeEntity']] = None, - suggestion_id: Optional[str] = None, - attachments: Optional[List['MessageInputAttachment']] = None, - analytics: Optional['RequestAnalytics'] = None, - options: Optional['StatelessMessageInputOptions'] = None, + streaming_metadata: 'Metadata', ) -> None: """ - Initialize a StatelessMessageInput object. + Initialize a CompleteItem object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the - Segment extension. - :param StatelessMessageInputOptions options: (optional) Optional properties - that control how the assistant responds. + :param Metadata streaming_metadata: """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.analytics = analytics - self.options = options + # pylint: disable=super-init-not-called + self.streaming_metadata = streaming_metadata @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageInput': - """Initialize a StatelessMessageInput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CompleteItem': + """Initialize a CompleteItem object from a json dictionary.""" args = {} - if (message_type := _dict.get('message_type')) is not None: - args['message_type'] = message_type - if (text := _dict.get('text')) is not None: - args['text'] = text - if (intents := _dict.get('intents')) is not None: - args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] - if (entities := _dict.get('entities')) is not None: - args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] - if (suggestion_id := _dict.get('suggestion_id')) is not None: - args['suggestion_id'] = suggestion_id - if (attachments := _dict.get('attachments')) is not None: - args['attachments'] = [ - MessageInputAttachment.from_dict(v) for v in attachments - ] - if (analytics := _dict.get('analytics')) is not None: - args['analytics'] = RequestAnalytics.from_dict(analytics) - if (options := _dict.get('options')) is not None: - args['options'] = StatelessMessageInputOptions.from_dict(options) + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = Metadata.from_dict(streaming_metadata) + else: + raise ValueError( + 'Required property \'streaming_metadata\' not present in CompleteItem JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageInput object from a json dictionary.""" + """Initialize a CompleteItem object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - attachments_list = [] - for v in self.attachments: - if isinstance(v, dict): - attachments_list.append(v) - else: - attachments_list.append(v.to_dict()) - _dict['attachments'] = attachments_list - if hasattr(self, 'analytics') and self.analytics is not None: - if isinstance(self.analytics, dict): - _dict['analytics'] = self.analytics - else: - _dict['analytics'] = self.analytics.to_dict() - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options + if hasattr( + self, + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata else: - _dict['options'] = self.options.to_dict() + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() return _dict def _to_dict(self): @@ -10965,133 +15547,155 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageInput object.""" + """Return a `str` version of this CompleteItem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageInput') -> bool: + def __eq__(self, other: 'CompleteItem') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'StatelessMessageInput') -> bool: + def __ne__(self, other: 'CompleteItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): + +class LogMessageSourceAction(LogMessageSource): + """ + An object that identifies the dialog element that generated the error message. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. + """ + + def __init__( + self, + type: str, + action: str, + ) -> None: """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. + Initialize a LogMessageSourceAction object. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. """ + # pylint: disable=super-init-not-called + self.type = type + self.action = action - TEXT = 'text' - SEARCH = 'search' + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': + """Initialize a LogMessageSourceAction object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceAction JSON' + ) + if (action := _dict.get('action')) is not None: + args['action'] = action + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceAction JSON' + ) + return cls(**args) + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogMessageSourceAction object from a json dictionary.""" + return cls.from_dict(_dict) -class StatelessMessageInputOptions: - """ - Optional properties that control how the assistant responds. + 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, 'action') and self.action is not None: + _dict['action'] = self.action + return _dict - :param bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param bool async_callout: (optional) Whether custom extension callouts are - executed asynchronously. Asynchronous execution means the response to the - extension callout will be processed on the subsequent message call, the initial - message response signals to the client that the operation may be long running. - With synchronous execution the custom extension is executed and returns the - response in a single message turn. **Note:** **async_callout** defaults to true - for API versions earlier than 2023-06-15. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __str__(self) -> str: + """Return a `str` version of this LogMessageSourceAction object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogMessageSourceAction') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ + + def __ne__(self, other: 'LogMessageSourceAction') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogMessageSourceDialogNode(LogMessageSource): + """ + An object that identifies the dialog element that generated the error message. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str dialog_node: The unique identifier of the dialog node that generated + the error message. """ def __init__( self, - *, - restart: Optional[bool] = None, - alternate_intents: Optional[bool] = None, - async_callout: Optional[bool] = None, - spelling: Optional['MessageInputOptionsSpelling'] = None, - debug: Optional[bool] = None, + type: str, + dialog_node: str, ) -> None: """ - Initialize a StatelessMessageInputOptions object. + Initialize a LogMessageSourceDialogNode object. - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param bool async_callout: (optional) Whether custom extension callouts are - executed asynchronously. Asynchronous execution means the response to the - extension callout will be processed on the subsequent message call, the - initial message response signals to the client that the operation may be - long running. With synchronous execution the custom extension is executed - and returns the response in a single message turn. **Note:** - **async_callout** defaults to true for API versions earlier than - 2023-06-15. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str dialog_node: The unique identifier of the dialog node that + generated the error message. """ - self.restart = restart - self.alternate_intents = alternate_intents - self.async_callout = async_callout - self.spelling = spelling - self.debug = debug + # pylint: disable=super-init-not-called + self.type = type + self.dialog_node = dialog_node @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageInputOptions': - """Initialize a StatelessMessageInputOptions object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': + """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" args = {} - if (restart := _dict.get('restart')) is not None: - args['restart'] = restart - if (alternate_intents := _dict.get('alternate_intents')) is not None: - args['alternate_intents'] = alternate_intents - if (async_callout := _dict.get('async_callout')) is not None: - args['async_callout'] = async_callout - if (spelling := _dict.get('spelling')) is not None: - args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) - if (debug := _dict.get('debug')) is not None: - args['debug'] = debug + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' + ) + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + else: + raise ValueError( + 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageInputOptions object from a json dictionary.""" + """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'restart') and self.restart is not None: - _dict['restart'] = self.restart - if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'async_callout') and self.async_callout is not None: - _dict['async_callout'] = self.async_callout - if hasattr(self, 'spelling') and self.spelling is not None: - if isinstance(self.spelling, dict): - _dict['spelling'] = self.spelling - else: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node return _dict def _to_dict(self): @@ -11099,137 +15703,102 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageInputOptions object.""" + """Return a `str` version of this LogMessageSourceDialogNode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageInputOptions') -> bool: + def __eq__(self, other: 'LogMessageSourceDialogNode') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'StatelessMessageInputOptions') -> bool: + def __ne__(self, other: 'LogMessageSourceDialogNode') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageResponse: +class LogMessageSourceHandler(LogMessageSource): """ - A stateless response from the watsonx Assistant service. + An object that identifies the dialog element that generated the error message. - :param MessageOutput output: Assistant output to be rendered or processed by the - client. - :param StatelessMessageContext context: Context data for the conversation. You - can use this property to access context variables. The context is not stored by - the assistant; to maintain session state, include the context from the response - in the next message. - :param MessageOutput masked_output: (optional) Assistant output to be rendered - or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes the - input text. All private data is masked or removed. - :param str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. + :param str step: (optional) The unique identifier of the step that generated the + error message. + :param str handler: The unique identifier of the handler that generated the + error message. """ def __init__( self, - output: 'MessageOutput', - context: 'StatelessMessageContext', + type: str, + action: str, + handler: str, *, - masked_output: Optional['MessageOutput'] = None, - masked_input: Optional['MessageInput'] = None, - user_id: Optional[str] = None, + step: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageResponse object. + Initialize a LogMessageSourceHandler object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param StatelessMessageContext context: Context data for the conversation. - You can use this property to access context variables. The context is not - stored by the assistant; to maintain session state, include the context - from the response in the next message. - :param MessageOutput masked_output: (optional) Assistant output to be - rendered or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes - the input text. All private data is masked or removed. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str handler: The unique identifier of the handler that generated the + error message. + :param str step: (optional) The unique identifier of the step that + generated the error message. """ - self.output = output - self.context = context - self.masked_output = masked_output - self.masked_input = masked_input - self.user_id = user_id + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step + self.handler = handler @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageResponse': - """Initialize a StatelessMessageResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': + """Initialize a LogMessageSourceHandler object from a json dictionary.""" args = {} - if (output := _dict.get('output')) is not None: - args['output'] = MessageOutput.from_dict(output) + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( - 'Required property \'output\' not present in StatelessMessageResponse JSON' + 'Required property \'type\' not present in LogMessageSourceHandler JSON' ) - if (context := _dict.get('context')) is not None: - args['context'] = StatelessMessageContext.from_dict(context) + if (action := _dict.get('action')) is not None: + args['action'] = action else: raise ValueError( - 'Required property \'context\' not present in StatelessMessageResponse JSON' + 'Required property \'action\' not present in LogMessageSourceHandler JSON' + ) + if (step := _dict.get('step')) is not None: + args['step'] = step + if (handler := _dict.get('handler')) is not None: + args['handler'] = handler + else: + raise ValueError( + 'Required property \'handler\' not present in LogMessageSourceHandler JSON' ) - if (masked_output := _dict.get('masked_output')) is not None: - args['masked_output'] = MessageOutput.from_dict(masked_output) - if (masked_input := _dict.get('masked_input')) is not None: - args['masked_input'] = MessageInput.from_dict(masked_input) - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageResponse object from a json dictionary.""" + """Initialize a LogMessageSourceHandler object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'masked_output') and self.masked_output is not None: - if isinstance(self.masked_output, dict): - _dict['masked_output'] = self.masked_output - else: - _dict['masked_output'] = self.masked_output.to_dict() - if hasattr(self, 'masked_input') and self.masked_input is not None: - if isinstance(self.masked_input, dict): - _dict['masked_input'] = self.masked_input - else: - _dict['masked_input'] = self.masked_input.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'handler') and self.handler is not None: + _dict['handler'] = self.handler return _dict def _to_dict(self): @@ -11237,58 +15806,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageResponse object.""" + """Return a `str` version of this LogMessageSourceHandler object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageResponse') -> bool: + def __eq__(self, other: 'LogMessageSourceHandler') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'StatelessMessageResponse') -> bool: + def __ne__(self, other: 'LogMessageSourceHandler') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatusError: +class LogMessageSourceStep(LogMessageSource): """ - An object describing an error that occurred during processing of an asynchronous - operation. + An object that identifies the dialog element that generated the error message. - :param str message: (optional) The text of the error message. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. + :param str step: The unique identifier of the step that generated the error + message. """ def __init__( self, - *, - message: Optional[str] = None, + type: str, + action: str, + step: str, ) -> None: """ - Initialize a StatusError object. + Initialize a LogMessageSourceStep object. - :param str message: (optional) The text of the error message. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str step: The unique identifier of the step that generated the error + message. """ - self.message = message + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step @classmethod - def from_dict(cls, _dict: Dict) -> 'StatusError': - """Initialize a StatusError object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': + """Initialize a LogMessageSourceStep object from a json dictionary.""" args = {} - if (message := _dict.get('message')) is not None: - args['message'] = message + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceStep JSON' + ) + if (action := _dict.get('action')) is not None: + args['action'] = action + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceStep JSON' + ) + if (step := _dict.get('step')) is not None: + args['step'] = step + else: + raise ValueError( + 'Required property \'step\' not present in LogMessageSourceStep JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatusError object from a json dictionary.""" + """Initialize a LogMessageSourceStep object from 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') and self.message is not None: - _dict['message'] = self.message + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step return _dict def _to_dict(self): @@ -11296,84 +15898,112 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatusError object.""" + """Return a `str` version of this LogMessageSourceStep object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatusError') -> bool: + def __eq__(self, other: 'LogMessageSourceStep') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'StatusError') -> bool: + def __ne__(self, other: 'LogMessageSourceStep') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TurnEventActionSource: +class MessageOutputDebugTurnEventTurnEventActionFinished( + MessageOutputDebugTurnEvent): """ - TurnEventActionSource. + MessageOutputDebugTurnEventTurnEventActionFinished. - :param str type: (optional) The type of turn event. - :param str action: (optional) An action that was visited during processing of - the message. - :param str action_title: (optional) The title of the action. - :param str condition: (optional) The condition that triggered the dialog node. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables at + the time the action finished. """ def __init__( self, *, - type: Optional[str] = None, - action: Optional[str] = None, - action_title: Optional[str] = None, - condition: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + action_variables: Optional[dict] = None, ) -> None: """ - Initialize a TurnEventActionSource object. + Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object. - :param str type: (optional) The type of turn event. - :param str action: (optional) An action that was visited during processing - of the message. - :param str action_title: (optional) The title of the action. - :param str condition: (optional) The condition that triggered the dialog - node. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables + at the time the action finished. """ - self.type = type - self.action = action - self.action_title = action_title - self.condition = condition + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason + self.action_variables = action_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventActionSource': - """Initialize a TurnEventActionSource object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventActionFinished': + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (action := _dict.get('action')) is not None: - args['action'] = action - if (action_title := _dict.get('action_title')) is not None: - args['action_title'] = action_title - if (condition := _dict.get('condition')) is not None: - args['condition'] = condition + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventActionSource object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from 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, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'action_title') and self.action_title is not None: - _dict['action_title'] = self.action_title - if hasattr(self, 'condition') and self.condition is not None: - _dict['condition'] = self.condition + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables return _dict def _to_dict(self): @@ -11381,82 +16011,135 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventActionSource object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionFinished object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventActionSource') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TurnEventActionSource') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): + class ConditionTypeEnum(str, Enum): """ - The type of turn event. + The type of condition (if any) that is defined for the action. """ - ACTION = 'action' + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + class ReasonEnum(str, Enum): + """ + The reason the action finished processing. + """ -class TurnEventCalloutCallout: + ALL_STEPS_DONE = 'all_steps_done' + NO_STEPS_VISITED = 'no_steps_visited' + ENDED_BY_STEP = 'ended_by_step' + CONNECT_TO_AGENT = 'connect_to_agent' + MAX_RETRIES_REACHED = 'max_retries_reached' + FALLBACK = 'fallback' + + +class MessageOutputDebugTurnEventTurnEventActionVisited( + MessageOutputDebugTurnEvent): """ - TurnEventCalloutCallout. + MessageOutputDebugTurnEventTurnEventActionVisited. - :param str type: (optional) The type of callout. Currently, the only supported - value is `integration_interaction` (for calls to extensions). - :param dict internal: (optional) For internal use only. - :param str result_variable: (optional) The name of the variable where the - callout result is stored. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the call + to the action is stored. Included only if **reason**=`subaction_return`. """ def __init__( self, *, - type: Optional[str] = None, - internal: Optional[dict] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, result_variable: Optional[str] = None, ) -> None: """ - Initialize a TurnEventCalloutCallout object. + Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. - :param str type: (optional) The type of callout. Currently, the only - supported value is `integration_interaction` (for calls to extensions). - :param dict internal: (optional) For internal use only. - :param str result_variable: (optional) The name of the variable where the - callout result is stored. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the + call to the action is stored. Included only if + **reason**=`subaction_return`. """ - self.type = type - self.internal = internal + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason self.result_variable = result_variable @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': - """Initialize a TurnEventCalloutCallout object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventActionVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (internal := _dict.get('internal')) is not None: - args['internal'] = internal + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason if (result_variable := _dict.get('result_variable')) is not None: args['result_variable'] = result_variable return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventCalloutCallout object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from 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, 'internal') and self.internal is not None: - _dict['internal'] = self.internal + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason if hasattr(self, 'result_variable') and self.result_variable is not None: _dict['result_variable'] = self.result_variable @@ -11467,67 +16150,120 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventCalloutCallout object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventCalloutCallout') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TurnEventCalloutCallout') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): + class ConditionTypeEnum(str, Enum): """ - The type of callout. Currently, the only supported value is - `integration_interaction` (for calls to extensions). + The type of condition (if any) that is defined for the action. """ - INTEGRATION_INTERACTION = 'integration_interaction' + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + class ReasonEnum(str, Enum): + """ + The reason the action was visited. + """ -class TurnEventCalloutError: + INTENT = 'intent' + INVOKE_SUBACTION = 'invoke_subaction' + SUBACTION_RETURN = 'subaction_return' + INVOKE_EXTERNAL = 'invoke_external' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + AGENT_REQUESTED = 'agent_requested' + STEP_VALIDATION_FAILED = 'step_validation_failed' + NO_ACTION_MATCHES = 'no_action_matches' + + +class MessageOutputDebugTurnEventTurnEventCallout(MessageOutputDebugTurnEvent): """ - TurnEventCalloutError. + MessageOutputDebugTurnEventTurnEventCallout. - :param str message: (optional) Any error message returned by a failed call to an - external service. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ def __init__( self, *, - message: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + callout: Optional['TurnEventCalloutCallout'] = None, + error: Optional['TurnEventCalloutError'] = None, ) -> None: """ - Initialize a TurnEventCalloutError object. + Initialize a MessageOutputDebugTurnEventTurnEventCallout object. - :param str message: (optional) Any error message returned by a failed call - to an external service. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ - self.message = message + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.callout = callout + self.error = error @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutError': - """Initialize a TurnEventCalloutError object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventCallout': + """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" args = {} - if (message := _dict.get('message')) is not None: - args['message'] = message + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (callout := _dict.get('callout')) is not None: + args['callout'] = TurnEventCalloutCallout.from_dict(callout) + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventCalloutError.from_dict(error) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventCalloutError object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from 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') and self.message is not None: - _dict['message'] = self.message + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'callout') and self.callout is not None: + if isinstance(self.callout, dict): + _dict['callout'] = self.callout + else: + _dict['callout'] = self.callout.to_dict() + if hasattr(self, 'error') and self.error is not None: + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -11535,84 +16271,85 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventCalloutError object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventCallout object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventCalloutError') -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TurnEventCalloutError') -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TurnEventNodeSource: +class MessageOutputDebugTurnEventTurnEventHandlerVisited( + MessageOutputDebugTurnEvent): """ - TurnEventNodeSource. + MessageOutputDebugTurnEventTurnEventHandlerVisited. - :param str type: (optional) The type of turn event. - :param str dialog_node: (optional) A dialog node that was visited during - processing of the input message. - :param str title: (optional) The title of the dialog node. - :param str condition: (optional) The condition that triggered the dialog node. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. """ def __init__( self, *, - type: Optional[str] = None, - dialog_node: Optional[str] = None, - title: Optional[str] = None, - condition: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, ) -> None: """ - Initialize a TurnEventNodeSource object. + Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object. - :param str type: (optional) The type of turn event. - :param str dialog_node: (optional) A dialog node that was visited during - processing of the input message. - :param str title: (optional) The title of the dialog node. - :param str condition: (optional) The condition that triggered the dialog - node. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. """ - self.type = type - self.dialog_node = dialog_node - self.title = title - self.condition = condition + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventNodeSource': - """Initialize a TurnEventNodeSource object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventHandlerVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (dialog_node := _dict.get('dialog_node')) is not None: - args['dialog_node'] = dialog_node - if (title := _dict.get('title')) is not None: - args['title'] = title - if (condition := _dict.get('condition')) is not None: - args['condition'] = condition + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventNodeSource object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from 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, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'condition') and self.condition is not None: - _dict['condition'] = self.condition + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time return _dict def _to_dict(self): @@ -11620,66 +16357,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventNodeSource object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventHandlerVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventNodeSource') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TurnEventNodeSource') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of turn event. - """ - - DIALOG_NODE = 'dialog_node' - -class TurnEventSearchError: +class MessageOutputDebugTurnEventTurnEventNodeVisited( + MessageOutputDebugTurnEvent): """ - TurnEventSearchError. + MessageOutputDebugTurnEventTurnEventNodeVisited. - :param str message: (optional) Any error message returned by a failed call to a - search skill. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ def __init__( self, *, - message: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventNodeSource'] = None, + reason: Optional[str] = None, ) -> None: """ - Initialize a TurnEventSearchError object. + Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object. - :param str message: (optional) Any error message returned by a failed call - to a search skill. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ - self.message = message + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.reason = reason @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError': - """Initialize a TurnEventSearchError object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventNodeVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" args = {} - if (message := _dict.get('message')) is not None: - args['message'] = message + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventNodeSource.from_dict(source) + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventSearchError object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from 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') and self.message is not None: - _dict['message'] = self.message + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason return _dict def _to_dict(self): @@ -11687,77 +16442,97 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventSearchError object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventNodeVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventSearchError') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'TurnEventSearchError') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ReasonEnum(str, Enum): + """ + The reason the dialog node was visited. + """ + + WELCOME = 'welcome' + BRANCH_START = 'branch_start' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + TOPIC_SWITCH_WITHOUT_RETURN = 'topic_switch_without_return' + JUMP = 'jump' -class LogMessageSourceAction(LogMessageSource): + +class MessageOutputDebugTurnEventTurnEventSearch(MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventSearch. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the error - message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventSearchError error: (optional) """ def __init__( self, - type: str, - action: str, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + error: Optional['TurnEventSearchError'] = None, ) -> None: """ - Initialize a LogMessageSourceAction object. + Initialize a MessageOutputDebugTurnEventTurnEventSearch object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventSearchError error: (optional) """ # pylint: disable=super-init-not-called - self.type = type - self.action = action + self.event = event + self.source = source + self.error = error @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': - """Initialize a LogMessageSourceAction object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventSearch': + """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceAction JSON' - ) - if (action := _dict.get('action')) is not None: - args['action'] = action - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceAction JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventSearchError.from_dict(error) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceAction object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from 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, 'action') and self.action is not None: - _dict['action'] = self.action + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'error') and self.error is not None: + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -11765,77 +16540,107 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceAction object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventSearch object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceAction') -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogMessageSourceAction') -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSourceDialogNode(LogMessageSource): +class MessageOutputDebugTurnEventTurnEventStepAnswered( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventStepAnswered. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str dialog_node: The unique identifier of the dialog node that generated - the error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool prompted: (optional) Whether the step was answered in response to a + prompt from the assistant. If this property is `false`, the user provided the + answer without visiting the step. """ def __init__( self, - type: str, - dialog_node: str, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + prompted: Optional[bool] = None, ) -> None: """ - Initialize a LogMessageSourceDialogNode object. + Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str dialog_node: The unique identifier of the dialog node that - generated the error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool prompted: (optional) Whether the step was answered in response + to a prompt from the assistant. If this property is `false`, the user + provided the answer without visiting the step. """ # pylint: disable=super-init-not-called - self.type = type - self.dialog_node = dialog_node + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.prompted = prompted @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepAnswered': + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' - ) - if (dialog_node := _dict.get('dialog_node')) is not None: - args['dialog_node'] = dialog_node - else: - raise ValueError( - 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (prompted := _dict.get('prompted')) is not None: + args['prompted'] = prompted return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from 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, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'prompted') and self.prompted is not None: + _dict['prompted'] = self.prompted return _dict def _to_dict(self): @@ -11843,102 +16648,116 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceDialogNode object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepAnswered object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceDialogNode') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogMessageSourceDialogNode') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ -class LogMessageSourceHandler(LogMessageSource): + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + +class MessageOutputDebugTurnEventTurnEventStepVisited( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventStepVisited. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the error - message. - :param str step: (optional) The unique identifier of the step that generated the - error message. - :param str handler: The unique identifier of the handler that generated the - error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool has_question: (optional) Whether the step collects a customer + response. """ def __init__( self, - type: str, - action: str, - handler: str, *, - step: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + has_question: Optional[bool] = None, ) -> None: """ - Initialize a LogMessageSourceHandler object. + Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str handler: The unique identifier of the handler that generated the - error message. - :param str step: (optional) The unique identifier of the step that - generated the error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool has_question: (optional) Whether the step collects a customer + response. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step - self.handler = handler + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.has_question = has_question @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': - """Initialize a LogMessageSourceHandler object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceHandler JSON' - ) - if (action := _dict.get('action')) is not None: - args['action'] = action - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceHandler JSON' - ) - if (step := _dict.get('step')) is not None: - args['step'] = step - if (handler := _dict.get('handler')) is not None: - args['handler'] = handler - else: - raise ValueError( - 'Required property \'handler\' not present in LogMessageSourceHandler JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (has_question := _dict.get('has_question')) is not None: + args['has_question'] = has_question return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceHandler object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from 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, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step - if hasattr(self, 'handler') and self.handler is not None: - _dict['handler'] = self.handler + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'has_question') and self.has_question is not None: + _dict['has_question'] = self.has_question return _dict def _to_dict(self): @@ -11946,91 +16765,124 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceHandler object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceHandler') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogMessageSourceHandler') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ -class LogMessageSourceStep(LogMessageSource): - """ - An object that identifies the dialog element that generated the error message. + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the error - message. - :param str step: The unique identifier of the step that generated the error - message. + +class ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode( + ProviderAuthenticationOAuth2Flows): + """ + Non-private authentication settings for authorization-code flow. + + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param str authorization_url: (optional) The authorization URL. + :param str redirect_uri: (optional) The redirect URI. """ def __init__( self, - type: str, - action: str, - step: str, + *, + token_url: Optional[str] = None, + refresh_url: Optional[str] = None, + client_auth_type: Optional[str] = None, + content_type: Optional[str] = None, + header_prefix: Optional[str] = None, + authorization_url: Optional[str] = None, + redirect_uri: Optional[str] = None, ) -> None: """ - Initialize a LogMessageSourceStep object. + Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str step: The unique identifier of the step that generated the error - message. + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param str authorization_url: (optional) The authorization URL. + :param str redirect_uri: (optional) The redirect URI. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step + self.token_url = token_url + self.refresh_url = refresh_url + self.client_auth_type = client_auth_type + self.content_type = content_type + self.header_prefix = header_prefix + self.authorization_url = authorization_url + self.redirect_uri = redirect_uri @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': - """Initialize a LogMessageSourceStep object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode': + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceStep JSON' - ) - if (action := _dict.get('action')) is not None: - args['action'] = action - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceStep JSON' - ) - if (step := _dict.get('step')) is not None: - args['step'] = step - else: - raise ValueError( - 'Required property \'step\' not present in LogMessageSourceStep JSON' - ) + if (token_url := _dict.get('token_url')) is not None: + args['token_url'] = token_url + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + if (client_auth_type := _dict.get('client_auth_type')) is not None: + args['client_auth_type'] = client_auth_type + if (content_type := _dict.get('content_type')) is not None: + args['content_type'] = content_type + if (header_prefix := _dict.get('header_prefix')) is not None: + args['header_prefix'] = header_prefix + if (authorization_url := _dict.get('authorization_url')) is not None: + args['authorization_url'] = authorization_url + if (redirect_uri := _dict.get('redirect_uri')) is not None: + args['redirect_uri'] = redirect_uri return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceStep object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode object from 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, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step + if hasattr(self, 'token_url') and self.token_url is not None: + _dict['token_url'] = self.token_url + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, + 'client_auth_type') and self.client_auth_type is not None: + _dict['client_auth_type'] = self.client_auth_type + if hasattr(self, 'content_type') and self.content_type is not None: + _dict['content_type'] = self.content_type + if hasattr(self, 'header_prefix') and self.header_prefix is not None: + _dict['header_prefix'] = self.header_prefix + if hasattr(self, + 'authorization_url') and self.authorization_url is not None: + _dict['authorization_url'] = self.authorization_url + if hasattr(self, 'redirect_uri') and self.redirect_uri is not None: + _dict['redirect_uri'] = self.redirect_uri return _dict def _to_dict(self): @@ -12038,112 +16890,108 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceStep object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceStep') -> bool: + def __eq__( + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, other: 'LogMessageSourceStep') -> bool: + def __ne__( + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ClientAuthTypeEnum(str, Enum): + """ + The client authorization type. + """ -class MessageOutputDebugTurnEventTurnEventActionFinished( - MessageOutputDebugTurnEvent): + BODY = 'Body' + BASICAUTHHEADER = 'BasicAuthHeader' + + +class ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials( + ProviderAuthenticationOAuth2Flows): """ - MessageOutputDebugTurnEventTurnEventActionFinished. + ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. - :param str condition_type: (optional) The type of condition (if any) that is - defined for the action. - :param str reason: (optional) The reason the action finished processing. - :param dict action_variables: (optional) The state of all action variables at - the time the action finished. + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - action_start_time: Optional[str] = None, - condition_type: Optional[str] = None, - reason: Optional[str] = None, - action_variables: Optional[dict] = None, + token_url: Optional[str] = None, + refresh_url: Optional[str] = None, + client_auth_type: Optional[str] = None, + content_type: Optional[str] = None, + header_prefix: Optional[str] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object. + Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. - :param str condition_type: (optional) The type of condition (if any) that - is defined for the action. - :param str reason: (optional) The reason the action finished processing. - :param dict action_variables: (optional) The state of all action variables - at the time the action finished. + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.action_start_time = action_start_time - self.condition_type = condition_type - self.reason = reason - self.action_variables = action_variables + self.token_url = token_url + self.refresh_url = refresh_url + self.client_auth_type = client_auth_type + self.content_type = content_type + self.header_prefix = header_prefix @classmethod def from_dict( - cls, _dict: Dict - ) -> 'MessageOutputDebugTurnEventTurnEventActionFinished': - """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" + cls, _dict: Dict + ) -> 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials': + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time - if (condition_type := _dict.get('condition_type')) is not None: - args['condition_type'] = condition_type - if (reason := _dict.get('reason')) is not None: - args['reason'] = reason - if (action_variables := _dict.get('action_variables')) is not None: - args['action_variables'] = action_variables + if (token_url := _dict.get('token_url')) is not None: + args['token_url'] = token_url + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + if (client_auth_type := _dict.get('client_auth_type')) is not None: + args['client_auth_type'] = client_auth_type + if (content_type := _dict.get('content_type')) is not None: + args['content_type'] = content_type + if (header_prefix := _dict.get('header_prefix')) is not None: + args['header_prefix'] = header_prefix return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials object from 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') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time - if hasattr(self, 'condition_type') and self.condition_type is not None: - _dict['condition_type'] = self.condition_type - if hasattr(self, 'reason') and self.reason is not None: - _dict['reason'] = self.reason + if hasattr(self, 'token_url') and self.token_url is not None: + _dict['token_url'] = self.token_url + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url if hasattr(self, - 'action_variables') and self.action_variables is not None: - _dict['action_variables'] = self.action_variables + 'client_auth_type') and self.client_auth_type is not None: + _dict['client_auth_type'] = self.client_auth_type + if hasattr(self, 'content_type') and self.content_type is not None: + _dict['content_type'] = self.content_type + if hasattr(self, 'header_prefix') and self.header_prefix is not None: + _dict['header_prefix'] = self.header_prefix return _dict def _to_dict(self): @@ -12151,11 +16999,12 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionFinished object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials' ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): @@ -12163,126 +17012,112 @@ def __eq__( return self.__dict__ == other.__dict__ def __ne__( - self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials' ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConditionTypeEnum(str, Enum): - """ - The type of condition (if any) that is defined for the action. - """ - - USER_DEFINED = 'user_defined' - WELCOME = 'welcome' - ANYTHING_ELSE = 'anything_else' - - class ReasonEnum(str, Enum): + class ClientAuthTypeEnum(str, Enum): """ - The reason the action finished processing. + The client authorization type. """ - ALL_STEPS_DONE = 'all_steps_done' - NO_STEPS_VISITED = 'no_steps_visited' - ENDED_BY_STEP = 'ended_by_step' - CONNECT_TO_AGENT = 'connect_to_agent' - MAX_RETRIES_REACHED = 'max_retries_reached' - FALLBACK = 'fallback' + BODY = 'Body' + BASICAUTHHEADER = 'BasicAuthHeader' -class MessageOutputDebugTurnEventTurnEventActionVisited( - MessageOutputDebugTurnEvent): +class ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password( + ProviderAuthenticationOAuth2Flows): """ - MessageOutputDebugTurnEventTurnEventActionVisited. - - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. - :param str condition_type: (optional) The type of condition (if any) that is - defined for the action. - :param str reason: (optional) The reason the action was visited. - :param str result_variable: (optional) The variable where the result of the call - to the action is stored. Included only if **reason**=`subaction_return`. + Non-private authentication settings for resource owner password flow. + + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param ProviderAuthenticationOAuth2PasswordUsername username: (optional) The + username for oauth2 authentication when the preferred flow is "password". """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - action_start_time: Optional[str] = None, - condition_type: Optional[str] = None, - reason: Optional[str] = None, - result_variable: Optional[str] = None, + token_url: Optional[str] = None, + refresh_url: Optional[str] = None, + client_auth_type: Optional[str] = None, + content_type: Optional[str] = None, + header_prefix: Optional[str] = None, + username: Optional[ + 'ProviderAuthenticationOAuth2PasswordUsername'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. + Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. - :param str condition_type: (optional) The type of condition (if any) that - is defined for the action. - :param str reason: (optional) The reason the action was visited. - :param str result_variable: (optional) The variable where the result of the - call to the action is stored. Included only if - **reason**=`subaction_return`. + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param ProviderAuthenticationOAuth2PasswordUsername username: (optional) + The username for oauth2 authentication when the preferred flow is + "password". """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.action_start_time = action_start_time - self.condition_type = condition_type - self.reason = reason - self.result_variable = result_variable + self.token_url = token_url + self.refresh_url = refresh_url + self.client_auth_type = client_auth_type + self.content_type = content_type + self.header_prefix = header_prefix + self.username = username @classmethod def from_dict( - cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventActionVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" + cls, _dict: Dict + ) -> 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password': + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time - if (condition_type := _dict.get('condition_type')) is not None: - args['condition_type'] = condition_type - if (reason := _dict.get('reason')) is not None: - args['reason'] = reason - if (result_variable := _dict.get('result_variable')) is not None: - args['result_variable'] = result_variable + if (token_url := _dict.get('token_url')) is not None: + args['token_url'] = token_url + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + if (client_auth_type := _dict.get('client_auth_type')) is not None: + args['client_auth_type'] = client_auth_type + if (content_type := _dict.get('content_type')) is not None: + args['content_type'] = content_type + if (header_prefix := _dict.get('header_prefix')) is not None: + args['header_prefix'] = header_prefix + if (username := _dict.get('username')) is not None: + args[ + 'username'] = ProviderAuthenticationOAuth2PasswordUsername.from_dict( + username) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password object from 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') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time - if hasattr(self, 'condition_type') and self.condition_type is not None: - _dict['condition_type'] = self.condition_type - if hasattr(self, 'reason') and self.reason is not None: - _dict['reason'] = self.reason + if hasattr(self, 'token_url') and self.token_url is not None: + _dict['token_url'] = self.token_url + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url if hasattr(self, - 'result_variable') and self.result_variable is not None: - _dict['result_variable'] = self.result_variable + 'client_auth_type') and self.client_auth_type is not None: + _dict['client_auth_type'] = self.client_auth_type + if hasattr(self, 'content_type') and self.content_type is not None: + _dict['content_type'] = self.content_type + if hasattr(self, 'header_prefix') and self.header_prefix is not None: + _dict['header_prefix'] = self.header_prefix + if hasattr(self, 'username') and self.username is not None: + if isinstance(self.username, dict): + _dict['username'] = self.username + else: + _dict['username'] = self.username.to_dict() return _dict def _to_dict(self): @@ -12290,120 +17125,78 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionVisited object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, - other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__( - self, - other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConditionTypeEnum(str, Enum): - """ - The type of condition (if any) that is defined for the action. - """ - - USER_DEFINED = 'user_defined' - WELCOME = 'welcome' - ANYTHING_ELSE = 'anything_else' - - class ReasonEnum(str, Enum): + class ClientAuthTypeEnum(str, Enum): """ - The reason the action was visited. + The client authorization type. """ - INTENT = 'intent' - INVOKE_SUBACTION = 'invoke_subaction' - SUBACTION_RETURN = 'subaction_return' - INVOKE_EXTERNAL = 'invoke_external' - TOPIC_SWITCH = 'topic_switch' - TOPIC_RETURN = 'topic_return' - AGENT_REQUESTED = 'agent_requested' - STEP_VALIDATION_FAILED = 'step_validation_failed' - NO_ACTION_MATCHES = 'no_action_matches' + BODY = 'Body' + BASICAUTHHEADER = 'BasicAuthHeader' -class MessageOutputDebugTurnEventTurnEventCallout(MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationBasicFlow(ProviderPrivateAuthentication): """ - MessageOutputDebugTurnEventTurnEventCallout. + The private data for basic authentication. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param TurnEventCalloutCallout callout: (optional) - :param TurnEventCalloutError error: (optional) + :param ProviderAuthenticationTypeAndValue password: (optional) The password for + bearer authentication. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - callout: Optional['TurnEventCalloutCallout'] = None, - error: Optional['TurnEventCalloutError'] = None, + password: Optional['ProviderAuthenticationTypeAndValue'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventCallout object. + Initialize a ProviderPrivateAuthenticationBasicFlow object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param TurnEventCalloutCallout callout: (optional) - :param TurnEventCalloutError error: (optional) + :param ProviderAuthenticationTypeAndValue password: (optional) The password + for bearer authentication. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.callout = callout - self.error = error + self.password = password @classmethod - def from_dict(cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventCallout': - """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderPrivateAuthenticationBasicFlow': + """Initialize a ProviderPrivateAuthenticationBasicFlow object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (callout := _dict.get('callout')) is not None: - args['callout'] = TurnEventCalloutCallout.from_dict(callout) - if (error := _dict.get('error')) is not None: - args['error'] = TurnEventCalloutError.from_dict(error) + if (password := _dict.get('password')) is not None: + args['password'] = ProviderAuthenticationTypeAndValue.from_dict( + password) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationBasicFlow object from 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') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source + if hasattr(self, 'password') and self.password is not None: + if isinstance(self.password, dict): + _dict['password'] = self.password else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'callout') and self.callout is not None: - if isinstance(self.callout, dict): - _dict['callout'] = self.callout - else: - _dict['callout'] = self.callout.to_dict() - if hasattr(self, 'error') and self.error is not None: - if isinstance(self.error, dict): - _dict['error'] = self.error - else: - _dict['error'] = self.error.to_dict() + _dict['password'] = self.password.to_dict() return _dict def _to_dict(self): @@ -12411,85 +17204,64 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventCallout object.""" + """Return a `str` version of this ProviderPrivateAuthenticationBasicFlow object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: + def __eq__(self, other: 'ProviderPrivateAuthenticationBasicFlow') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, - other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: + def __ne__(self, other: 'ProviderPrivateAuthenticationBasicFlow') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebugTurnEventTurnEventHandlerVisited( - MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationBearerFlow(ProviderPrivateAuthentication): """ - MessageOutputDebugTurnEventTurnEventHandlerVisited. + The private data for bearer authentication. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. + :param ProviderAuthenticationTypeAndValue token: (optional) The token for bearer + authentication. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - action_start_time: Optional[str] = None, + token: Optional['ProviderAuthenticationTypeAndValue'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object. + Initialize a ProviderPrivateAuthenticationBearerFlow object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. + :param ProviderAuthenticationTypeAndValue token: (optional) The token for + bearer authentication. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.action_start_time = action_start_time + self.token = token @classmethod - def from_dict( - cls, _dict: Dict - ) -> 'MessageOutputDebugTurnEventTurnEventHandlerVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'ProviderPrivateAuthenticationBearerFlow': + """Initialize a ProviderPrivateAuthenticationBearerFlow object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time + if (token := _dict.get('token')) is not None: + args['token'] = ProviderAuthenticationTypeAndValue.from_dict(token) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationBearerFlow object from 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') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source + if hasattr(self, 'token') and self.token is not None: + if isinstance(self.token, dict): + _dict['token'] = self.token else: - _dict['source'] = self.source.to_dict() - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time + _dict['token'] = self.token.to_dict() return _dict def _to_dict(self): @@ -12497,84 +17269,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventHandlerVisited object.""" + """Return a `str` version of this ProviderPrivateAuthenticationBearerFlow object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' - ) -> bool: + def __eq__(self, other: 'ProviderPrivateAuthenticationBearerFlow') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__( - self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' - ) -> bool: + def __ne__(self, other: 'ProviderPrivateAuthenticationBearerFlow') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebugTurnEventTurnEventNodeVisited( - MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationOAuth2Flow(ProviderPrivateAuthentication): """ - MessageOutputDebugTurnEventTurnEventNodeVisited. + The private data for oauth2 authentication. - :param str event: (optional) The type of turn event. - :param TurnEventNodeSource source: (optional) - :param str reason: (optional) The reason the dialog node was visited. + :param ProviderPrivateAuthenticationOAuth2FlowFlows flows: (optional) Scenarios + performed by the API client to fetch an access token from the authorization + server. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventNodeSource'] = None, - reason: Optional[str] = None, + flows: Optional['ProviderPrivateAuthenticationOAuth2FlowFlows'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object. + Initialize a ProviderPrivateAuthenticationOAuth2Flow object. - :param str event: (optional) The type of turn event. - :param TurnEventNodeSource source: (optional) - :param str reason: (optional) The reason the dialog node was visited. + :param ProviderPrivateAuthenticationOAuth2FlowFlows flows: (optional) + Scenarios performed by the API client to fetch an access token from the + authorization server. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.reason = reason + self.flows = flows @classmethod - def from_dict( - cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventNodeVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'ProviderPrivateAuthenticationOAuth2Flow': + """Initialize a ProviderPrivateAuthenticationOAuth2Flow object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventNodeSource.from_dict(source) - if (reason := _dict.get('reason')) is not None: - args['reason'] = reason + if (flows := _dict.get('flows')) is not None: + args['flows'] = flows return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2Flow object from 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') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source + if hasattr(self, 'flows') and self.flows is not None: + if isinstance(self.flows, dict): + _dict['flows'] = self.flows else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'reason') and self.reason is not None: - _dict['reason'] = self.reason + _dict['flows'] = self.flows.to_dict() return _dict def _to_dict(self): @@ -12582,97 +17336,95 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventNodeVisited object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2Flow object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, - other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: + def __eq__(self, other: 'ProviderPrivateAuthenticationOAuth2Flow') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__( - self, - other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: + def __ne__(self, other: 'ProviderPrivateAuthenticationOAuth2Flow') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ReasonEnum(str, Enum): - """ - The reason the dialog node was visited. - """ - - WELCOME = 'welcome' - BRANCH_START = 'branch_start' - TOPIC_SWITCH = 'topic_switch' - TOPIC_RETURN = 'topic_return' - TOPIC_SWITCH_WITHOUT_RETURN = 'topic_switch_without_return' - JUMP = 'jump' - -class MessageOutputDebugTurnEventTurnEventSearch(MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode( + ProviderPrivateAuthenticationOAuth2FlowFlows): """ - MessageOutputDebugTurnEventTurnEventSearch. + Private authentication settings for client credentials flow. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param TurnEventSearchError error: (optional) + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param str authorization_code: (optional) The authorization code. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - error: Optional['TurnEventSearchError'] = None, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + access_token: Optional[str] = None, + refresh_token: Optional[str] = None, + authorization_code: Optional[str] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventSearch object. + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param TurnEventSearchError error: (optional) + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param str authorization_code: (optional) The authorization code. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.error = error + self.client_id = client_id + self.client_secret = client_secret + self.access_token = access_token + self.refresh_token = refresh_token + self.authorization_code = authorization_code @classmethod - def from_dict(cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventSearch': - """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode': + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (error := _dict.get('error')) is not None: - args['error'] = TurnEventSearchError.from_dict(error) + if (client_id := _dict.get('client_id')) is not None: + args['client_id'] = client_id + if (client_secret := _dict.get('client_secret')) is not None: + args['client_secret'] = client_secret + if (access_token := _dict.get('access_token')) is not None: + args['access_token'] = access_token + if (refresh_token := _dict.get('refresh_token')) is not None: + args['refresh_token'] = refresh_token + if (authorization_code := _dict.get('authorization_code')) is not None: + args['authorization_code'] = authorization_code return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode object from 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') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'error') and self.error is not None: - if isinstance(self.error, dict): - _dict['error'] = self.error - else: - _dict['error'] = self.error.to_dict() + if hasattr(self, 'client_id') and self.client_id is not None: + _dict['client_id'] = self.client_id + if hasattr(self, 'client_secret') and self.client_secret is not None: + _dict['client_secret'] = self.client_secret + if hasattr(self, 'access_token') and self.access_token is not None: + _dict['access_token'] = self.access_token + if hasattr(self, 'refresh_token') and self.refresh_token is not None: + _dict['refresh_token'] = self.refresh_token + if hasattr( + self, + 'authorization_code') and self.authorization_code is not None: + _dict['authorization_code'] = self.authorization_code return _dict def _to_dict(self): @@ -12680,107 +17432,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventSearch object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: + def __eq__( + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ - def __ne__(self, - other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: + def __ne__( + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebugTurnEventTurnEventStepAnswered( - MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials( + ProviderPrivateAuthenticationOAuth2FlowFlows): """ - MessageOutputDebugTurnEventTurnEventStepAnswered. + ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that is - defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool prompted: (optional) Whether the step was answered in response to a - prompt from the assistant. If this property is `false`, the user provided the - answer without visiting the step. + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - condition_type: Optional[str] = None, - action_start_time: Optional[str] = None, - prompted: Optional[bool] = None, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + access_token: Optional[str] = None, + refresh_token: Optional[str] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object. + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that - is defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool prompted: (optional) Whether the step was answered in response - to a prompt from the assistant. If this property is `false`, the user - provided the answer without visiting the step. + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.condition_type = condition_type - self.action_start_time = action_start_time - self.prompted = prompted + self.client_id = client_id + self.client_secret = client_secret + self.access_token = access_token + self.refresh_token = refresh_token @classmethod def from_dict( - cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepAnswered': - """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials': + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (condition_type := _dict.get('condition_type')) is not None: - args['condition_type'] = condition_type - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time - if (prompted := _dict.get('prompted')) is not None: - args['prompted'] = prompted + if (client_id := _dict.get('client_id')) is not None: + args['client_id'] = client_id + if (client_secret := _dict.get('client_secret')) is not None: + args['client_secret'] = client_secret + if (access_token := _dict.get('access_token')) is not None: + args['access_token'] = access_token + if (refresh_token := _dict.get('refresh_token')) is not None: + args['refresh_token'] = refresh_token return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials object from 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') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'condition_type') and self.condition_type is not None: - _dict['condition_type'] = self.condition_type - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time - if hasattr(self, 'prompted') and self.prompted is not None: - _dict['prompted'] = self.prompted + if hasattr(self, 'client_id') and self.client_id is not None: + _dict['client_id'] = self.client_id + if hasattr(self, 'client_secret') and self.client_secret is not None: + _dict['client_secret'] = self.client_secret + if hasattr(self, 'access_token') and self.access_token is not None: + _dict['access_token'] = self.access_token + if hasattr(self, 'refresh_token') and self.refresh_token is not None: + _dict['refresh_token'] = self.refresh_token return _dict def _to_dict(self): @@ -12788,116 +17524,108 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepAnswered object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, - other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__( - self, - other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConditionTypeEnum(str, Enum): - """ - The type of condition (if any) that is defined for the action. - """ - - USER_DEFINED = 'user_defined' - WELCOME = 'welcome' - ANYTHING_ELSE = 'anything_else' - -class MessageOutputDebugTurnEventTurnEventStepVisited( - MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password( + ProviderPrivateAuthenticationOAuth2FlowFlows): """ - MessageOutputDebugTurnEventTurnEventStepVisited. - - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that is - defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool has_question: (optional) Whether the step collects a customer - response. + Private authentication settings for resource owner password flow. + + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param ProviderPrivateAuthenticationOAuth2PasswordPassword password: (optional) + The password for oauth2 authentication when the preferred flow is "password". """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - condition_type: Optional[str] = None, - action_start_time: Optional[str] = None, - has_question: Optional[bool] = None, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + access_token: Optional[str] = None, + refresh_token: Optional[str] = None, + password: Optional[ + 'ProviderPrivateAuthenticationOAuth2PasswordPassword'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object. + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that - is defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool has_question: (optional) Whether the step collects a customer - response. + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param ProviderPrivateAuthenticationOAuth2PasswordPassword password: + (optional) The password for oauth2 authentication when the preferred flow + is "password". """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.condition_type = condition_type - self.action_start_time = action_start_time - self.has_question = has_question + self.client_id = client_id + self.client_secret = client_secret + self.access_token = access_token + self.refresh_token = refresh_token + self.password = password @classmethod def from_dict( - cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password': + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (condition_type := _dict.get('condition_type')) is not None: - args['condition_type'] = condition_type - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time - if (has_question := _dict.get('has_question')) is not None: - args['has_question'] = has_question + if (client_id := _dict.get('client_id')) is not None: + args['client_id'] = client_id + if (client_secret := _dict.get('client_secret')) is not None: + args['client_secret'] = client_secret + if (access_token := _dict.get('access_token')) is not None: + args['access_token'] = access_token + if (refresh_token := _dict.get('refresh_token')) is not None: + args['refresh_token'] = refresh_token + if (password := _dict.get('password')) is not None: + args[ + 'password'] = ProviderPrivateAuthenticationOAuth2PasswordPassword.from_dict( + password) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password object from 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') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source + if hasattr(self, 'client_id') and self.client_id is not None: + _dict['client_id'] = self.client_id + if hasattr(self, 'client_secret') and self.client_secret is not None: + _dict['client_secret'] = self.client_secret + if hasattr(self, 'access_token') and self.access_token is not None: + _dict['access_token'] = self.access_token + if hasattr(self, 'refresh_token') and self.refresh_token is not None: + _dict['refresh_token'] = self.refresh_token + if hasattr(self, 'password') and self.password is not None: + if isinstance(self.password, dict): + _dict['password'] = self.password else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'condition_type') and self.condition_type is not None: - _dict['condition_type'] = self.condition_type - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time - if hasattr(self, 'has_question') and self.has_question is not None: - _dict['has_question'] = self.has_question + _dict['password'] = self.password.to_dict() return _dict def _to_dict(self): @@ -12905,32 +17633,25 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepVisited object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, - other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password' + ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False return self.__dict__ == other.__dict__ def __ne__( - self, - other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConditionTypeEnum(str, Enum): - """ - The type of condition (if any) that is defined for the action. - """ - - USER_DEFINED = 'user_defined' - WELCOME = 'welcome' - ANYTHING_ELSE = 'anything_else' - class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): """ diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 181ca3b5..9ae2b0d2 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -21,11 +21,13 @@ from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect +import io import json import pytest import re import requests import responses +import tempfile import urllib from ibm_watson.assistant_v2 import * @@ -47,24 +49,560 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') +############################################################################## +# Start of Service: ConversationalSkillProviders +############################################################################## +# region + + +class TestCreateProvider: + """ + Test Class for create_provider + """ + + @responses.activate + def test_create_provider_all_params(self): + """ + create_provider() + """ + # Set up mock + url = preprocess_url('/v2/providers') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model + + # Set up parameter values + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model + + # Invoke method + response = _service.create_provider( + provider_id, + specification, + private, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['provider_id'] == 'testString' + assert req_body['specification'] == provider_specification_model + assert req_body['private'] == provider_private_model + + def test_create_provider_all_params_with_retries(self): + # Enable retries and run test_create_provider_all_params. + _service.enable_retries() + self.test_create_provider_all_params() + + # Disable retries and run test_create_provider_all_params. + _service.disable_retries() + self.test_create_provider_all_params() + + @responses.activate + def test_create_provider_value_error(self): + """ + test_create_provider_value_error() + """ + # Set up mock + url = preprocess_url('/v2/providers') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model + + # Set up parameter values + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "provider_id": provider_id, + "specification": specification, + "private": private, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_provider(**req_copy) + + def test_create_provider_value_error_with_retries(self): + # Enable retries and run test_create_provider_value_error. + _service.enable_retries() + self.test_create_provider_value_error() + + # Disable retries and run test_create_provider_value_error. + _service.disable_retries() + self.test_create_provider_value_error() + + +class TestListProviders: + """ + Test Class for list_providers + """ + + @responses.activate + def test_list_providers_all_params(self): + """ + list_providers() + """ + # Set up mock + url = preprocess_url('/v2/providers') + mock_response = '{"conversational_skill_providers": [{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + page_limit = 100 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False + + # Invoke method + response = _service.list_providers( + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_list_providers_all_params_with_retries(self): + # Enable retries and run test_list_providers_all_params. + _service.enable_retries() + self.test_list_providers_all_params() + + # Disable retries and run test_list_providers_all_params. + _service.disable_retries() + self.test_list_providers_all_params() + + @responses.activate + def test_list_providers_required_params(self): + """ + test_list_providers_required_params() + """ + # Set up mock + url = preprocess_url('/v2/providers') + mock_response = '{"conversational_skill_providers": [{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Invoke method + response = _service.list_providers() + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_providers_required_params_with_retries(self): + # Enable retries and run test_list_providers_required_params. + _service.enable_retries() + self.test_list_providers_required_params() + + # Disable retries and run test_list_providers_required_params. + _service.disable_retries() + self.test_list_providers_required_params() + + @responses.activate + def test_list_providers_value_error(self): + """ + test_list_providers_value_error() + """ + # Set up mock + url = preprocess_url('/v2/providers') + mock_response = '{"conversational_skill_providers": [{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_providers(**req_copy) + + def test_list_providers_value_error_with_retries(self): + # Enable retries and run test_list_providers_value_error. + _service.enable_retries() + self.test_list_providers_value_error() + + # Disable retries and run test_list_providers_value_error. + _service.disable_retries() + self.test_list_providers_value_error() + + +class TestUpdateProvider: + """ + Test Class for update_provider + """ + + @responses.activate + def test_update_provider_all_params(self): + """ + update_provider() + """ + # Set up mock + url = preprocess_url('/v2/providers/testString') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model + + # Set up parameter values + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model + + # Invoke method + response = _service.update_provider( + provider_id, + specification, + private, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['specification'] == provider_specification_model + assert req_body['private'] == provider_private_model + + def test_update_provider_all_params_with_retries(self): + # Enable retries and run test_update_provider_all_params. + _service.enable_retries() + self.test_update_provider_all_params() + + # Disable retries and run test_update_provider_all_params. + _service.disable_retries() + self.test_update_provider_all_params() + + @responses.activate + def test_update_provider_value_error(self): + """ + test_update_provider_value_error() + """ + # Set up mock + url = preprocess_url('/v2/providers/testString') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model + + # Set up parameter values + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "provider_id": provider_id, + "specification": specification, + "private": private, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_provider(**req_copy) + + def test_update_provider_value_error_with_retries(self): + # Enable retries and run test_update_provider_value_error. + _service.enable_retries() + self.test_update_provider_value_error() + + # Disable retries and run test_update_provider_value_error. + _service.disable_retries() + self.test_update_provider_value_error() + + +# endregion +############################################################################## +# End of Service: ConversationalSkillProviders +############################################################################## + ############################################################################## # Start of Service: Assistants ############################################################################## @@ -784,6 +1322,7 @@ def test_message_all_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' session_id = 'testString' input = message_input_model context = message_context_model @@ -792,6 +1331,7 @@ def test_message_all_params(self): # Invoke method response = _service.message( assistant_id, + environment_id, session_id, input=input, context=context, @@ -835,11 +1375,13 @@ def test_message_required_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' session_id = 'testString' # Invoke method response = _service.message( assistant_id, + environment_id, session_id, headers={}, ) @@ -875,11 +1417,13 @@ def test_message_value_error(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' session_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "environment_id": environment_id, "session_id": session_id, } for param in req_param_dict.keys(): @@ -1062,6 +1606,7 @@ def test_message_stateless_all_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' input = stateless_message_input_model context = stateless_message_context_model user_id = 'testString' @@ -1069,6 +1614,7 @@ def test_message_stateless_all_params(self): # Invoke method response = _service.message_stateless( assistant_id, + environment_id, input=input, context=context, user_id=user_id, @@ -1111,10 +1657,12 @@ def test_message_stateless_required_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' # Invoke method response = _service.message_stateless( assistant_id, + environment_id, headers={}, ) @@ -1149,10 +1697,12 @@ def test_message_stateless_value_error(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} @@ -1175,198 +1725,236 @@ def test_message_stateless_value_error_with_retries(self): ############################################################################## ############################################################################## -# Start of Service: BulkClassify +# Start of Service: MessageStream ############################################################################## # region -class TestBulkClassify: +class TestMessageStream: """ - Test Class for bulk_classify + Test Class for message_stream """ @responses.activate - def test_bulk_classify_all_params(self): + def test_message_stream_all_params(self): """ - bulk_classify() + message_stream() """ # Set up mock - url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message_stream') + mock_response = 'This is a mock binary response.' responses.add( responses.POST, url, body=mock_response, - content_type='application/json', + content_type='text/event-stream', status=200, ) - # Construct a dict representation of a BulkClassifyUtterance model - bulk_classify_utterance_model = {} - bulk_classify_utterance_model['text'] = 'testString' + # Construct a dict representation of a RuntimeIntent model + runtime_intent_model = {} + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' - # Set up parameter values - skill_id = 'testString' - input = [bulk_classify_utterance_model] + # Construct a dict representation of a CaptureGroup model + capture_group_model = {} + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] - # Invoke method - response = _service.bulk_classify( - skill_id, - input, - headers={}, - ) + # Construct a dict representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model = {} + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['input'] == [bulk_classify_utterance_model] + # Construct a dict representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model = {} + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 - def test_bulk_classify_all_params_with_retries(self): - # Enable retries and run test_bulk_classify_all_params. - _service.enable_retries() - self.test_bulk_classify_all_params() + # Construct a dict representation of a RuntimeEntityRole model + runtime_entity_role_model = {} + runtime_entity_role_model['type'] = 'date_from' - # Disable retries and run test_bulk_classify_all_params. - _service.disable_retries() - self.test_bulk_classify_all_params() + # Construct a dict representation of a RuntimeEntity model + runtime_entity_model = {} + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - @responses.activate - def test_bulk_classify_value_error(self): - """ - test_bulk_classify_value_error() - """ - # Set up mock - url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) + # Construct a dict representation of a MessageInputAttachment model + message_input_attachment_model = {} + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' - # Construct a dict representation of a BulkClassifyUtterance model - bulk_classify_utterance_model = {} - bulk_classify_utterance_model['text'] = 'testString' + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' - # Set up parameter values - skill_id = 'testString' - input = [bulk_classify_utterance_model] + # Construct a dict representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model = {} + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "skill_id": skill_id, - "input": input, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.bulk_classify(**req_copy) + # Construct a dict representation of a MessageInputOptions model + message_input_options_model = {} + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False - def test_bulk_classify_value_error_with_retries(self): - # Enable retries and run test_bulk_classify_value_error. - _service.enable_retries() - self.test_bulk_classify_value_error() + # Construct a dict representation of a MessageInput model + message_input_model = {} + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model - # Disable retries and run test_bulk_classify_value_error. - _service.disable_retries() - self.test_bulk_classify_value_error() + # Construct a dict representation of a MessageContextGlobalSystem model + message_context_global_system_model = {} + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + # Construct a dict representation of a MessageContextGlobal model + message_context_global_model = {} + message_context_global_model['system'] = message_context_global_system_model -# endregion -############################################################################## -# End of Service: BulkClassify -############################################################################## + # Construct a dict representation of a MessageContextSkillSystem model + message_context_skill_system_model = {} + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' -############################################################################## -# Start of Service: Logs -############################################################################## -# region + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Construct a dict representation of a MessageContextActionSkill model + message_context_action_skill_model = {} + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} -class TestListLogs: - """ - Test Class for list_logs - """ + # Construct a dict representation of a MessageContextSkills model + message_context_skills_model = {} + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - @responses.activate - def test_list_logs_all_params(self): - """ - list_logs() - """ - # Set up mock - url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) + # Construct a dict representation of a MessageContext model + message_context_model = {} + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} # Set up parameter values assistant_id = 'testString' - sort = 'testString' - filter = 'testString' - page_limit = 100 - cursor = 'testString' + environment_id = 'testString' + session_id = 'testString' + input = message_input_model + context = message_context_model + user_id = 'testString' # Invoke method - response = _service.list_logs( + response = _service.message_stream( assistant_id, - sort=sort, - filter=filter, - page_limit=page_limit, - cursor=cursor, + environment_id, + session_id, + input=input, + context=context, + user_id=user_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'sort={}'.format(sort) in query_string - assert 'filter={}'.format(filter) in query_string - assert 'page_limit={}'.format(page_limit) in query_string - assert 'cursor={}'.format(cursor) in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == message_input_model + assert req_body['context'] == message_context_model + assert req_body['user_id'] == 'testString' - def test_list_logs_all_params_with_retries(self): - # Enable retries and run test_list_logs_all_params. + def test_message_stream_all_params_with_retries(self): + # Enable retries and run test_message_stream_all_params. _service.enable_retries() - self.test_list_logs_all_params() + self.test_message_stream_all_params() - # Disable retries and run test_list_logs_all_params. + # Disable retries and run test_message_stream_all_params. _service.disable_retries() - self.test_list_logs_all_params() + self.test_message_stream_all_params() @responses.activate - def test_list_logs_required_params(self): + def test_message_stream_required_params(self): """ - test_list_logs_required_params() + test_message_stream_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message_stream') + mock_response = 'This is a mock binary response.' responses.add( - responses.GET, + responses.POST, url, body=mock_response, - content_type='application/json', + content_type='text/event-stream', status=200, ) # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' # Invoke method - response = _service.list_logs( + response = _service.message_stream( assistant_id, + environment_id, + session_id, headers={}, ) @@ -1374,304 +1962,465 @@ def test_list_logs_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 - def test_list_logs_required_params_with_retries(self): - # Enable retries and run test_list_logs_required_params. + def test_message_stream_required_params_with_retries(self): + # Enable retries and run test_message_stream_required_params. _service.enable_retries() - self.test_list_logs_required_params() + self.test_message_stream_required_params() - # Disable retries and run test_list_logs_required_params. + # Disable retries and run test_message_stream_required_params. _service.disable_retries() - self.test_list_logs_required_params() + self.test_message_stream_required_params() @responses.activate - def test_list_logs_value_error(self): + def test_message_stream_value_error(self): """ - test_list_logs_value_error() + test_message_stream_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message_stream') + mock_response = 'This is a mock binary response.' responses.add( - responses.GET, + responses.POST, url, body=mock_response, - content_type='application/json', + content_type='text/event-stream', status=200, ) # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "environment_id": environment_id, + "session_id": session_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_logs(**req_copy) + _service.message_stream(**req_copy) - def test_list_logs_value_error_with_retries(self): - # Enable retries and run test_list_logs_value_error. + def test_message_stream_value_error_with_retries(self): + # Enable retries and run test_message_stream_value_error. _service.enable_retries() - self.test_list_logs_value_error() + self.test_message_stream_value_error() - # Disable retries and run test_list_logs_value_error. + # Disable retries and run test_message_stream_value_error. _service.disable_retries() - self.test_list_logs_value_error() + self.test_message_stream_value_error() -# endregion -############################################################################## -# End of Service: Logs -############################################################################## +class TestMessageStreamStateless: + """ + Test Class for message_stream_stateless + """ -############################################################################## -# Start of Service: UserData -############################################################################## -# region + @responses.activate + def test_message_stream_stateless_all_params(self): + """ + message_stream_stateless() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/message_stream') + mock_response = 'This is a mock binary response.' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='text/event-stream', + status=200, + ) + + # Construct a dict representation of a RuntimeIntent model + runtime_intent_model = {} + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + # Construct a dict representation of a CaptureGroup model + capture_group_model = {} + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] -class TestDeleteUserData: - """ - Test Class for delete_user_data - """ + # Construct a dict representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model = {} + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + # Construct a dict representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model = {} + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + # Construct a dict representation of a RuntimeEntityRole model + runtime_entity_role_model = {} + runtime_entity_role_model['type'] = 'date_from' + + # Construct a dict representation of a RuntimeEntity model + runtime_entity_model = {} + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + # Construct a dict representation of a MessageInputAttachment model + message_input_attachment_model = {} + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + # Construct a dict representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model = {} + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a dict representation of a MessageInputOptions model + message_input_options_model = {} + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + # Construct a dict representation of a MessageInput model + message_input_model = {} + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a dict representation of a MessageContextGlobalSystem model + message_context_global_system_model = {} + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + # Construct a dict representation of a MessageContextGlobal model + message_context_global_model = {} + message_context_global_model['system'] = message_context_global_system_model + + # Construct a dict representation of a MessageContextSkillSystem model + message_context_skill_system_model = {} + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a MessageContextActionSkill model + message_context_action_skill_model = {} + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a MessageContextSkills model + message_context_skills_model = {} + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + # Construct a dict representation of a MessageContext model + message_context_model = {} + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + input = message_input_model + context = message_context_model + user_id = 'testString' + + # Invoke method + response = _service.message_stream_stateless( + assistant_id, + environment_id, + input=input, + context=context, + user_id=user_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == message_input_model + assert req_body['context'] == message_context_model + assert req_body['user_id'] == 'testString' + + def test_message_stream_stateless_all_params_with_retries(self): + # Enable retries and run test_message_stream_stateless_all_params. + _service.enable_retries() + self.test_message_stream_stateless_all_params() + + # Disable retries and run test_message_stream_stateless_all_params. + _service.disable_retries() + self.test_message_stream_stateless_all_params() @responses.activate - def test_delete_user_data_all_params(self): + def test_message_stream_stateless_required_params(self): """ - delete_user_data() + test_message_stream_stateless_required_params() """ # Set up mock - url = preprocess_url('/v2/user_data') + url = preprocess_url('/v2/assistants/testString/environments/testString/message_stream') + mock_response = 'This is a mock binary response.' responses.add( - responses.DELETE, + responses.POST, url, - status=202, + body=mock_response, + content_type='text/event-stream', + status=200, ) # Set up parameter values - customer_id = 'testString' + assistant_id = 'testString' + environment_id = 'testString' # Invoke method - response = _service.delete_user_data( - customer_id, + response = _service.message_stream_stateless( + assistant_id, + environment_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'customer_id={}'.format(customer_id) in query_string + assert response.status_code == 200 - def test_delete_user_data_all_params_with_retries(self): - # Enable retries and run test_delete_user_data_all_params. + def test_message_stream_stateless_required_params_with_retries(self): + # Enable retries and run test_message_stream_stateless_required_params. _service.enable_retries() - self.test_delete_user_data_all_params() + self.test_message_stream_stateless_required_params() - # Disable retries and run test_delete_user_data_all_params. + # Disable retries and run test_message_stream_stateless_required_params. _service.disable_retries() - self.test_delete_user_data_all_params() + self.test_message_stream_stateless_required_params() @responses.activate - def test_delete_user_data_value_error(self): + def test_message_stream_stateless_value_error(self): """ - test_delete_user_data_value_error() + test_message_stream_stateless_value_error() """ # Set up mock - url = preprocess_url('/v2/user_data') + url = preprocess_url('/v2/assistants/testString/environments/testString/message_stream') + mock_response = 'This is a mock binary response.' responses.add( - responses.DELETE, + responses.POST, url, - status=202, + body=mock_response, + content_type='text/event-stream', + status=200, ) # Set up parameter values - customer_id = 'testString' + assistant_id = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { - "customer_id": customer_id, + "assistant_id": assistant_id, + "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_user_data(**req_copy) + _service.message_stream_stateless(**req_copy) - def test_delete_user_data_value_error_with_retries(self): - # Enable retries and run test_delete_user_data_value_error. + def test_message_stream_stateless_value_error_with_retries(self): + # Enable retries and run test_message_stream_stateless_value_error. _service.enable_retries() - self.test_delete_user_data_value_error() + self.test_message_stream_stateless_value_error() - # Disable retries and run test_delete_user_data_value_error. + # Disable retries and run test_message_stream_stateless_value_error. _service.disable_retries() - self.test_delete_user_data_value_error() + self.test_message_stream_stateless_value_error() # endregion ############################################################################## -# End of Service: UserData +# End of Service: MessageStream ############################################################################## ############################################################################## -# Start of Service: Environments +# Start of Service: BulkClassify ############################################################################## # region -class TestListEnvironments: +class TestBulkClassify: """ - Test Class for list_environments + Test Class for bulk_classify """ @responses.activate - def test_list_environments_all_params(self): + def test_bulk_classify_all_params(self): """ - list_environments() + bulk_classify() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments') - mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', status=200, ) - # Set up parameter values - assistant_id = 'testString' - page_limit = 100 - include_count = False - sort = 'name' - cursor = 'testString' - include_audit = False - - # Invoke method - response = _service.list_environments( - assistant_id, - page_limit=page_limit, - include_count=include_count, - sort=sort, - cursor=cursor, - include_audit=include_audit, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'page_limit={}'.format(page_limit) in query_string - assert 'include_count={}'.format('true' if include_count else 'false') in query_string - assert 'sort={}'.format(sort) in query_string - assert 'cursor={}'.format(cursor) in query_string - assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - - def test_list_environments_all_params_with_retries(self): - # Enable retries and run test_list_environments_all_params. - _service.enable_retries() - self.test_list_environments_all_params() - - # Disable retries and run test_list_environments_all_params. - _service.disable_retries() - self.test_list_environments_all_params() - - @responses.activate - def test_list_environments_required_params(self): - """ - test_list_environments_required_params() - """ - # Set up mock - url = preprocess_url('/v2/assistants/testString/environments') - mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' # Set up parameter values - assistant_id = 'testString' + skill_id = 'testString' + input = [bulk_classify_utterance_model] # Invoke method - response = _service.list_environments( - assistant_id, + response = _service.bulk_classify( + skill_id, + input, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == [bulk_classify_utterance_model] - def test_list_environments_required_params_with_retries(self): - # Enable retries and run test_list_environments_required_params. + def test_bulk_classify_all_params_with_retries(self): + # Enable retries and run test_bulk_classify_all_params. _service.enable_retries() - self.test_list_environments_required_params() + self.test_bulk_classify_all_params() - # Disable retries and run test_list_environments_required_params. + # Disable retries and run test_bulk_classify_all_params. _service.disable_retries() - self.test_list_environments_required_params() + self.test_bulk_classify_all_params() @responses.activate - def test_list_environments_value_error(self): + def test_bulk_classify_value_error(self): """ - test_list_environments_value_error() + test_bulk_classify_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments') - mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', status=200, ) + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' + # Set up parameter values - assistant_id = 'testString' + skill_id = 'testString' + input = [bulk_classify_utterance_model] # Pass in all but one required param and check for a ValueError req_param_dict = { - "assistant_id": assistant_id, + "skill_id": skill_id, + "input": input, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_environments(**req_copy) + _service.bulk_classify(**req_copy) - def test_list_environments_value_error_with_retries(self): - # Enable retries and run test_list_environments_value_error. + def test_bulk_classify_value_error_with_retries(self): + # Enable retries and run test_bulk_classify_value_error. _service.enable_retries() - self.test_list_environments_value_error() + self.test_bulk_classify_value_error() - # Disable retries and run test_list_environments_value_error. + # Disable retries and run test_bulk_classify_value_error. _service.disable_retries() - self.test_list_environments_value_error() + self.test_bulk_classify_value_error() -class TestGetEnvironment: +# endregion +############################################################################## +# End of Service: BulkClassify +############################################################################## + +############################################################################## +# Start of Service: Logs +############################################################################## +# region + + +class TestListLogs: """ - Test Class for get_environment + Test Class for list_logs """ @responses.activate - def test_get_environment_all_params(self): + def test_list_logs_all_params(self): """ - get_environment() + list_logs() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -1682,14 +2431,18 @@ def test_get_environment_all_params(self): # Set up parameter values assistant_id = 'testString' - environment_id = 'testString' - include_audit = False + sort = 'testString' + filter = 'testString' + page_limit = 100 + cursor = 'testString' # Invoke method - response = _service.get_environment( + response = _service.list_logs( assistant_id, - environment_id, - include_audit=include_audit, + sort=sort, + filter=filter, + page_limit=page_limit, + cursor=cursor, headers={}, ) @@ -1699,25 +2452,28 @@ def test_get_environment_all_params(self): # Validate query params query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) - assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'filter={}'.format(filter) in query_string + assert 'page_limit={}'.format(page_limit) in query_string + assert 'cursor={}'.format(cursor) in query_string - def test_get_environment_all_params_with_retries(self): - # Enable retries and run test_get_environment_all_params. + def test_list_logs_all_params_with_retries(self): + # Enable retries and run test_list_logs_all_params. _service.enable_retries() - self.test_get_environment_all_params() + self.test_list_logs_all_params() - # Disable retries and run test_get_environment_all_params. + # Disable retries and run test_list_logs_all_params. _service.disable_retries() - self.test_get_environment_all_params() + self.test_list_logs_all_params() @responses.activate - def test_get_environment_required_params(self): + def test_list_logs_required_params(self): """ - test_get_environment_required_params() + test_list_logs_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -1728,12 +2484,10 @@ def test_get_environment_required_params(self): # Set up parameter values assistant_id = 'testString' - environment_id = 'testString' # Invoke method - response = _service.get_environment( + response = _service.list_logs( assistant_id, - environment_id, headers={}, ) @@ -1741,23 +2495,23 @@ def test_get_environment_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 - def test_get_environment_required_params_with_retries(self): - # Enable retries and run test_get_environment_required_params. + def test_list_logs_required_params_with_retries(self): + # Enable retries and run test_list_logs_required_params. _service.enable_retries() - self.test_get_environment_required_params() + self.test_list_logs_required_params() - # Disable retries and run test_get_environment_required_params. + # Disable retries and run test_list_logs_required_params. _service.disable_retries() - self.test_get_environment_required_params() + self.test_list_logs_required_params() @responses.activate - def test_get_environment_value_error(self): + def test_list_logs_value_error(self): """ - test_get_environment_value_error() + test_list_logs_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -1768,293 +2522,240 @@ def test_get_environment_value_error(self): # Set up parameter values assistant_id = 'testString' - environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_environment(**req_copy) + _service.list_logs(**req_copy) - def test_get_environment_value_error_with_retries(self): - # Enable retries and run test_get_environment_value_error. + def test_list_logs_value_error_with_retries(self): + # Enable retries and run test_list_logs_value_error. _service.enable_retries() - self.test_get_environment_value_error() + self.test_list_logs_value_error() - # Disable retries and run test_get_environment_value_error. + # Disable retries and run test_list_logs_value_error. _service.disable_retries() - self.test_get_environment_value_error() + self.test_list_logs_value_error() -class TestUpdateEnvironment: +# endregion +############################################################################## +# End of Service: Logs +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + + +class TestDeleteUserData: """ - Test Class for update_environment + Test Class for delete_user_data """ @responses.activate - def test_update_environment_all_params(self): + def test_delete_user_data_all_params(self): """ - update_environment() + delete_user_data() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/user_data') responses.add( - responses.POST, + responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=200, + status=202, ) - # Construct a dict representation of a BaseEnvironmentOrchestration model - base_environment_orchestration_model = {} - base_environment_orchestration_model['search_skill_fallback'] = True - - # Construct a dict representation of a EnvironmentSkill model - environment_skill_model = {} - environment_skill_model['skill_id'] = 'testString' - environment_skill_model['type'] = 'dialog' - environment_skill_model['disabled'] = True - environment_skill_model['snapshot'] = 'testString' - environment_skill_model['skill_reference'] = 'testString' - # Set up parameter values - assistant_id = 'testString' - environment_id = 'testString' - name = 'testString' - description = 'testString' - orchestration = base_environment_orchestration_model - session_timeout = 10 - skill_references = [environment_skill_model] - - # Invoke method - response = _service.update_environment( - assistant_id, - environment_id, - name=name, - description=description, - orchestration=orchestration, - session_timeout=session_timeout, - skill_references=skill_references, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['orchestration'] == base_environment_orchestration_model - assert req_body['session_timeout'] == 10 - assert req_body['skill_references'] == [environment_skill_model] - - def test_update_environment_all_params_with_retries(self): - # Enable retries and run test_update_environment_all_params. - _service.enable_retries() - self.test_update_environment_all_params() - - # Disable retries and run test_update_environment_all_params. - _service.disable_retries() - self.test_update_environment_all_params() - - @responses.activate - def test_update_environment_required_params(self): - """ - test_update_environment_required_params() - """ - # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - assistant_id = 'testString' - environment_id = 'testString' + customer_id = 'testString' # Invoke method - response = _service.update_environment( - assistant_id, - environment_id, + response = _service.delete_user_data( + customer_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'customer_id={}'.format(customer_id) in query_string - def test_update_environment_required_params_with_retries(self): - # Enable retries and run test_update_environment_required_params. + def test_delete_user_data_all_params_with_retries(self): + # Enable retries and run test_delete_user_data_all_params. _service.enable_retries() - self.test_update_environment_required_params() + self.test_delete_user_data_all_params() - # Disable retries and run test_update_environment_required_params. + # Disable retries and run test_delete_user_data_all_params. _service.disable_retries() - self.test_update_environment_required_params() + self.test_delete_user_data_all_params() @responses.activate - def test_update_environment_value_error(self): + def test_delete_user_data_value_error(self): """ - test_update_environment_value_error() + test_delete_user_data_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/user_data') responses.add( - responses.POST, + responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=200, + status=202, ) # Set up parameter values - assistant_id = 'testString' - environment_id = 'testString' + customer_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { - "assistant_id": assistant_id, - "environment_id": environment_id, + "customer_id": customer_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_environment(**req_copy) + _service.delete_user_data(**req_copy) - def test_update_environment_value_error_with_retries(self): - # Enable retries and run test_update_environment_value_error. + def test_delete_user_data_value_error_with_retries(self): + # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() - self.test_update_environment_value_error() + self.test_delete_user_data_value_error() - # Disable retries and run test_update_environment_value_error. + # Disable retries and run test_delete_user_data_value_error. _service.disable_retries() - self.test_update_environment_value_error() + self.test_delete_user_data_value_error() # endregion ############################################################################## -# End of Service: Environments +# End of Service: UserData ############################################################################## ############################################################################## -# Start of Service: Releases +# Start of Service: Environments ############################################################################## # region -class TestCreateRelease: +class TestListEnvironments: """ - Test Class for create_release + Test Class for list_environments """ @responses.activate - def test_create_release_all_params(self): + def test_list_environments_all_params(self): """ - create_release() + list_environments() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add( - responses.POST, + responses.GET, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) # Set up parameter values assistant_id = 'testString' - description = 'testString' + page_limit = 100 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False # Invoke method - response = _service.create_release( + response = _service.list_environments( assistant_id, - description=description, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['description'] == 'testString' + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - def test_create_release_all_params_with_retries(self): - # Enable retries and run test_create_release_all_params. + def test_list_environments_all_params_with_retries(self): + # Enable retries and run test_list_environments_all_params. _service.enable_retries() - self.test_create_release_all_params() + self.test_list_environments_all_params() - # Disable retries and run test_create_release_all_params. + # Disable retries and run test_list_environments_all_params. _service.disable_retries() - self.test_create_release_all_params() + self.test_list_environments_all_params() @responses.activate - def test_create_release_required_params(self): + def test_list_environments_required_params(self): """ - test_create_release_required_params() + test_list_environments_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add( - responses.POST, + responses.GET, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) # Set up parameter values assistant_id = 'testString' # Invoke method - response = _service.create_release( + response = _service.list_environments( assistant_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 + assert response.status_code == 200 - def test_create_release_required_params_with_retries(self): - # Enable retries and run test_create_release_required_params. + def test_list_environments_required_params_with_retries(self): + # Enable retries and run test_list_environments_required_params. _service.enable_retries() - self.test_create_release_required_params() + self.test_list_environments_required_params() - # Disable retries and run test_create_release_required_params. + # Disable retries and run test_list_environments_required_params. _service.disable_retries() - self.test_create_release_required_params() + self.test_list_environments_required_params() @responses.activate - def test_create_release_value_error(self): + def test_list_environments_value_error(self): """ - test_create_release_value_error() + test_list_environments_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add( - responses.POST, + responses.GET, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) # Set up parameter values @@ -2067,31 +2768,31 @@ def test_create_release_value_error(self): for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.create_release(**req_copy) + _service.list_environments(**req_copy) - def test_create_release_value_error_with_retries(self): - # Enable retries and run test_create_release_value_error. + def test_list_environments_value_error_with_retries(self): + # Enable retries and run test_list_environments_value_error. _service.enable_retries() - self.test_create_release_value_error() + self.test_list_environments_value_error() - # Disable retries and run test_create_release_value_error. + # Disable retries and run test_list_environments_value_error. _service.disable_retries() - self.test_create_release_value_error() + self.test_list_environments_value_error() -class TestListReleases: +class TestGetEnvironment: """ - Test Class for list_releases + Test Class for get_environment """ @responses.activate - def test_list_releases_all_params(self): + def test_get_environment_all_params(self): """ - list_releases() + get_environment() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.GET, url, @@ -2102,19 +2803,13 @@ def test_list_releases_all_params(self): # Set up parameter values assistant_id = 'testString' - page_limit = 100 - include_count = False - sort = 'name' - cursor = 'testString' + environment_id = 'testString' include_audit = False # Invoke method - response = _service.list_releases( + response = _service.get_environment( assistant_id, - page_limit=page_limit, - include_count=include_count, - sort=sort, - cursor=cursor, + environment_id, include_audit=include_audit, headers={}, ) @@ -2125,29 +2820,25 @@ def test_list_releases_all_params(self): # Validate query params query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) - assert 'page_limit={}'.format(page_limit) in query_string - assert 'include_count={}'.format('true' if include_count else 'false') in query_string - assert 'sort={}'.format(sort) in query_string - assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - def test_list_releases_all_params_with_retries(self): - # Enable retries and run test_list_releases_all_params. + def test_get_environment_all_params_with_retries(self): + # Enable retries and run test_get_environment_all_params. _service.enable_retries() - self.test_list_releases_all_params() + self.test_get_environment_all_params() - # Disable retries and run test_list_releases_all_params. + # Disable retries and run test_get_environment_all_params. _service.disable_retries() - self.test_list_releases_all_params() + self.test_get_environment_all_params() @responses.activate - def test_list_releases_required_params(self): + def test_get_environment_required_params(self): """ - test_list_releases_required_params() + test_get_environment_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.GET, url, @@ -2158,10 +2849,12 @@ def test_list_releases_required_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' # Invoke method - response = _service.list_releases( + response = _service.get_environment( assistant_id, + environment_id, headers={}, ) @@ -2169,23 +2862,23 @@ def test_list_releases_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 - def test_list_releases_required_params_with_retries(self): - # Enable retries and run test_list_releases_required_params. + def test_get_environment_required_params_with_retries(self): + # Enable retries and run test_get_environment_required_params. _service.enable_retries() - self.test_list_releases_required_params() + self.test_get_environment_required_params() - # Disable retries and run test_list_releases_required_params. + # Disable retries and run test_get_environment_required_params. _service.disable_retries() - self.test_list_releases_required_params() + self.test_get_environment_required_params() @responses.activate - def test_list_releases_value_error(self): + def test_get_environment_value_error(self): """ - test_list_releases_value_error() + test_get_environment_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.GET, url, @@ -2196,87 +2889,112 @@ def test_list_releases_value_error(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_releases(**req_copy) + _service.get_environment(**req_copy) - def test_list_releases_value_error_with_retries(self): - # Enable retries and run test_list_releases_value_error. + def test_get_environment_value_error_with_retries(self): + # Enable retries and run test_get_environment_value_error. _service.enable_retries() - self.test_list_releases_value_error() + self.test_get_environment_value_error() - # Disable retries and run test_list_releases_value_error. + # Disable retries and run test_get_environment_value_error. _service.disable_retries() - self.test_list_releases_value_error() + self.test_get_environment_value_error() -class TestGetRelease: +class TestUpdateEnvironment: """ - Test Class for get_release + Test Class for update_environment """ @responses.activate - def test_get_release_all_params(self): + def test_update_environment_all_params(self): """ - get_release() + update_environment() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', status=200, ) + # Construct a dict representation of a UpdateEnvironmentOrchestration model + update_environment_orchestration_model = {} + update_environment_orchestration_model['search_skill_fallback'] = True + + # Construct a dict representation of a EnvironmentSkill model + environment_skill_model = {} + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' + # Set up parameter values assistant_id = 'testString' - release = 'testString' - include_audit = False + environment_id = 'testString' + name = 'testString' + description = 'testString' + orchestration = update_environment_orchestration_model + session_timeout = 10 + skill_references = [environment_skill_model] # Invoke method - response = _service.get_release( + response = _service.update_environment( assistant_id, - release, - include_audit=include_audit, + environment_id, + name=name, + description=description, + orchestration=orchestration, + session_timeout=session_timeout, + skill_references=skill_references, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['orchestration'] == update_environment_orchestration_model + assert req_body['session_timeout'] == 10 + assert req_body['skill_references'] == [environment_skill_model] - def test_get_release_all_params_with_retries(self): - # Enable retries and run test_get_release_all_params. + def test_update_environment_all_params_with_retries(self): + # Enable retries and run test_update_environment_all_params. _service.enable_retries() - self.test_get_release_all_params() + self.test_update_environment_all_params() - # Disable retries and run test_get_release_all_params. + # Disable retries and run test_update_environment_all_params. _service.disable_retries() - self.test_get_release_all_params() + self.test_update_environment_all_params() @responses.activate - def test_get_release_required_params(self): + def test_update_environment_required_params(self): """ - test_get_release_required_params() + test_update_environment_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', @@ -2285,12 +3003,12 @@ def test_get_release_required_params(self): # Set up parameter values assistant_id = 'testString' - release = 'testString' + environment_id = 'testString' # Invoke method - response = _service.get_release( + response = _service.update_environment( assistant_id, - release, + environment_id, headers={}, ) @@ -2298,25 +3016,25 @@ def test_get_release_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 - def test_get_release_required_params_with_retries(self): - # Enable retries and run test_get_release_required_params. + def test_update_environment_required_params_with_retries(self): + # Enable retries and run test_update_environment_required_params. _service.enable_retries() - self.test_get_release_required_params() + self.test_update_environment_required_params() - # Disable retries and run test_get_release_required_params. + # Disable retries and run test_update_environment_required_params. _service.disable_retries() - self.test_get_release_required_params() + self.test_update_environment_required_params() @responses.activate - def test_get_release_value_error(self): + def test_update_environment_value_error(self): """ - test_get_release_value_error() + test_update_environment_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', @@ -2325,139 +3043,199 @@ def test_get_release_value_error(self): # Set up parameter values assistant_id = 'testString' - release = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "release": release, + "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_release(**req_copy) + _service.update_environment(**req_copy) - def test_get_release_value_error_with_retries(self): - # Enable retries and run test_get_release_value_error. + def test_update_environment_value_error_with_retries(self): + # Enable retries and run test_update_environment_value_error. _service.enable_retries() - self.test_get_release_value_error() + self.test_update_environment_value_error() - # Disable retries and run test_get_release_value_error. + # Disable retries and run test_update_environment_value_error. _service.disable_retries() - self.test_get_release_value_error() + self.test_update_environment_value_error() -class TestDeleteRelease: +# endregion +############################################################################## +# End of Service: Environments +############################################################################## + +############################################################################## +# Start of Service: Releases +############################################################################## +# region + + +class TestCreateRelease: """ - Test Class for delete_release + Test Class for create_release """ @responses.activate - def test_delete_release_all_params(self): + def test_create_release_all_params(self): """ - delete_release() + create_release() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString') + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.DELETE, + responses.POST, url, - status=200, + body=mock_response, + content_type='application/json', + status=202, ) # Set up parameter values assistant_id = 'testString' - release = 'testString' + description = 'testString' # Invoke method - response = _service.delete_release( + response = _service.create_release( assistant_id, - release, + description=description, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['description'] == 'testString' - def test_delete_release_all_params_with_retries(self): - # Enable retries and run test_delete_release_all_params. + def test_create_release_all_params_with_retries(self): + # Enable retries and run test_create_release_all_params. _service.enable_retries() - self.test_delete_release_all_params() + self.test_create_release_all_params() - # Disable retries and run test_delete_release_all_params. + # Disable retries and run test_create_release_all_params. _service.disable_retries() - self.test_delete_release_all_params() + self.test_create_release_all_params() @responses.activate - def test_delete_release_value_error(self): + def test_create_release_required_params(self): """ - test_delete_release_value_error() + test_create_release_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString') + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.DELETE, + responses.POST, url, - status=200, + body=mock_response, + content_type='application/json', + status=202, ) # Set up parameter values assistant_id = 'testString' - release = 'testString' - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "assistant_id": assistant_id, - "release": release, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_release(**req_copy) + # Invoke method + response = _service.create_release( + assistant_id, + headers={}, + ) - def test_delete_release_value_error_with_retries(self): - # Enable retries and run test_delete_release_value_error. + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_create_release_required_params_with_retries(self): + # Enable retries and run test_create_release_required_params. _service.enable_retries() - self.test_delete_release_value_error() + self.test_create_release_required_params() - # Disable retries and run test_delete_release_value_error. + # Disable retries and run test_create_release_required_params. _service.disable_retries() - self.test_delete_release_value_error() - - -class TestDeployRelease: - """ - Test Class for deploy_release - """ + self.test_create_release_required_params() @responses.activate - def test_deploy_release_all_params(self): + def test_create_release_value_error(self): """ - deploy_release() + test_create_release_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.POST, url, body=mock_response, content_type='application/json', + status=202, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_release(**req_copy) + + def test_create_release_value_error_with_retries(self): + # Enable retries and run test_create_release_value_error. + _service.enable_retries() + self.test_create_release_value_error() + + # Disable retries and run test_create_release_value_error. + _service.disable_retries() + self.test_create_release_value_error() + + +class TestListReleases: + """ + Test Class for list_releases + """ + + @responses.activate + def test_list_releases_all_params(self): + """ + list_releases() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', status=200, ) # Set up parameter values assistant_id = 'testString' - release = 'testString' - environment_id = 'testString' + page_limit = 100 + include_count = False + sort = 'name' + cursor = 'testString' include_audit = False # Invoke method - response = _service.deploy_release( + response = _service.list_releases( assistant_id, - release, - environment_id, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, include_audit=include_audit, headers={}, ) @@ -2468,30 +3246,31 @@ def test_deploy_release_all_params(self): # Validate query params query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['environment_id'] == 'testString' - def test_deploy_release_all_params_with_retries(self): - # Enable retries and run test_deploy_release_all_params. + def test_list_releases_all_params_with_retries(self): + # Enable retries and run test_list_releases_all_params. _service.enable_retries() - self.test_deploy_release_all_params() + self.test_list_releases_all_params() - # Disable retries and run test_deploy_release_all_params. + # Disable retries and run test_list_releases_all_params. _service.disable_retries() - self.test_deploy_release_all_params() + self.test_list_releases_all_params() @responses.activate - def test_deploy_release_required_params(self): + def test_list_releases_required_params(self): """ - test_deploy_release_required_params() + test_list_releases_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add( - responses.POST, + responses.GET, url, body=mock_response, content_type='application/json', @@ -2500,43 +3279,36 @@ def test_deploy_release_required_params(self): # Set up parameter values assistant_id = 'testString' - release = 'testString' - environment_id = 'testString' # Invoke method - response = _service.deploy_release( + response = _service.list_releases( assistant_id, - release, - environment_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['environment_id'] == 'testString' - def test_deploy_release_required_params_with_retries(self): - # Enable retries and run test_deploy_release_required_params. + def test_list_releases_required_params_with_retries(self): + # Enable retries and run test_list_releases_required_params. _service.enable_retries() - self.test_deploy_release_required_params() + self.test_list_releases_required_params() - # Disable retries and run test_deploy_release_required_params. + # Disable retries and run test_list_releases_required_params. _service.disable_retries() - self.test_deploy_release_required_params() + self.test_list_releases_required_params() @responses.activate - def test_deploy_release_value_error(self): + def test_list_releases_value_error(self): """ - test_deploy_release_value_error() + test_list_releases_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add( - responses.POST, + responses.GET, url, body=mock_response, content_type='application/json', @@ -2545,54 +3317,85 @@ def test_deploy_release_value_error(self): # Set up parameter values assistant_id = 'testString' - release = 'testString' - environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "release": release, - "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.deploy_release(**req_copy) + _service.list_releases(**req_copy) - def test_deploy_release_value_error_with_retries(self): - # Enable retries and run test_deploy_release_value_error. + def test_list_releases_value_error_with_retries(self): + # Enable retries and run test_list_releases_value_error. _service.enable_retries() - self.test_deploy_release_value_error() + self.test_list_releases_value_error() - # Disable retries and run test_deploy_release_value_error. + # Disable retries and run test_list_releases_value_error. _service.disable_retries() - self.test_deploy_release_value_error() + self.test_list_releases_value_error() -# endregion -############################################################################## -# End of Service: Releases -############################################################################## +class TestGetRelease: + """ + Test Class for get_release + """ -############################################################################## -# Start of Service: Skills -############################################################################## -# region + @responses.activate + def test_get_release_all_params(self): + """ + get_release() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + include_audit = False + # Invoke method + response = _service.get_release( + assistant_id, + release, + include_audit=include_audit, + headers={}, + ) -class TestGetSkill: - """ - Test Class for get_skill - """ + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_get_release_all_params_with_retries(self): + # Enable retries and run test_get_release_all_params. + _service.enable_retries() + self.test_get_release_all_params() + + # Disable retries and run test_get_release_all_params. + _service.disable_retries() + self.test_get_release_all_params() @responses.activate - def test_get_skill_all_params(self): + def test_get_release_required_params(self): """ - get_skill() + test_get_release_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.GET, url, @@ -2603,12 +3406,12 @@ def test_get_skill_all_params(self): # Set up parameter values assistant_id = 'testString' - skill_id = 'testString' + release = 'testString' # Invoke method - response = _service.get_skill( + response = _service.get_release( assistant_id, - skill_id, + release, headers={}, ) @@ -2616,23 +3419,23 @@ def test_get_skill_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 - def test_get_skill_all_params_with_retries(self): - # Enable retries and run test_get_skill_all_params. + def test_get_release_required_params_with_retries(self): + # Enable retries and run test_get_release_required_params. _service.enable_retries() - self.test_get_skill_all_params() + self.test_get_release_required_params() - # Disable retries and run test_get_skill_all_params. + # Disable retries and run test_get_release_required_params. _service.disable_retries() - self.test_get_skill_all_params() + self.test_get_release_required_params() @responses.activate - def test_get_skill_value_error(self): + def test_get_release_value_error(self): """ - test_get_skill_value_error() + test_get_release_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.GET, url, @@ -2643,220 +3446,122 @@ def test_get_skill_value_error(self): # Set up parameter values assistant_id = 'testString' - skill_id = 'testString' + release = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "skill_id": skill_id, + "release": release, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_skill(**req_copy) + _service.get_release(**req_copy) - def test_get_skill_value_error_with_retries(self): - # Enable retries and run test_get_skill_value_error. + def test_get_release_value_error_with_retries(self): + # Enable retries and run test_get_release_value_error. _service.enable_retries() - self.test_get_skill_value_error() + self.test_get_release_value_error() - # Disable retries and run test_get_skill_value_error. + # Disable retries and run test_get_release_value_error. _service.disable_retries() - self.test_get_skill_value_error() + self.test_get_release_value_error() -class TestUpdateSkill: +class TestDeleteRelease: """ - Test Class for update_skill + Test Class for delete_release """ @responses.activate - def test_update_skill_all_params(self): + def test_delete_release_all_params(self): """ - update_skill() + delete_release() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + url = preprocess_url('/v2/assistants/testString/releases/testString') responses.add( - responses.POST, + responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=202, + status=200, ) - # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model = {} - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - # Construct a dict representation of a SearchSettingsDiscovery model - search_settings_discovery_model = {} - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - # Construct a dict representation of a SearchSettingsMessages model - search_settings_messages_model = {} - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - # Construct a dict representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model = {} - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - # Construct a dict representation of a SearchSettings model - search_settings_model = {} - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - # Set up parameter values assistant_id = 'testString' - skill_id = 'testString' - name = 'testString' - description = 'testString' - workspace = {'anyKey': 'anyValue'} - dialog_settings = {'anyKey': 'anyValue'} - search_settings = search_settings_model + release = 'testString' # Invoke method - response = _service.update_skill( + response = _service.delete_release( assistant_id, - skill_id, - name=name, - description=description, - workspace=workspace, - dialog_settings=dialog_settings, - search_settings=search_settings, + release, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['workspace'] == {'anyKey': 'anyValue'} - assert req_body['dialog_settings'] == {'anyKey': 'anyValue'} - assert req_body['search_settings'] == search_settings_model + assert response.status_code == 200 - def test_update_skill_all_params_with_retries(self): - # Enable retries and run test_update_skill_all_params. + def test_delete_release_all_params_with_retries(self): + # Enable retries and run test_delete_release_all_params. _service.enable_retries() - self.test_update_skill_all_params() + self.test_delete_release_all_params() - # Disable retries and run test_update_skill_all_params. + # Disable retries and run test_delete_release_all_params. _service.disable_retries() - self.test_update_skill_all_params() + self.test_delete_release_all_params() @responses.activate - def test_update_skill_value_error(self): + def test_delete_release_value_error(self): """ - test_update_skill_value_error() + test_delete_release_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + url = preprocess_url('/v2/assistants/testString/releases/testString') responses.add( - responses.POST, + responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=202, + status=200, ) - # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model = {} - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - # Construct a dict representation of a SearchSettingsDiscovery model - search_settings_discovery_model = {} - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - # Construct a dict representation of a SearchSettingsMessages model - search_settings_messages_model = {} - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - # Construct a dict representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model = {} - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - # Construct a dict representation of a SearchSettings model - search_settings_model = {} - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - # Set up parameter values assistant_id = 'testString' - skill_id = 'testString' - name = 'testString' - description = 'testString' - workspace = {'anyKey': 'anyValue'} - dialog_settings = {'anyKey': 'anyValue'} - search_settings = search_settings_model + release = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "skill_id": skill_id, + "release": release, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_skill(**req_copy) + _service.delete_release(**req_copy) - def test_update_skill_value_error_with_retries(self): - # Enable retries and run test_update_skill_value_error. + def test_delete_release_value_error_with_retries(self): + # Enable retries and run test_delete_release_value_error. _service.enable_retries() - self.test_update_skill_value_error() + self.test_delete_release_value_error() - # Disable retries and run test_update_skill_value_error. + # Disable retries and run test_delete_release_value_error. _service.disable_retries() - self.test_update_skill_value_error() + self.test_delete_release_value_error() -class TestExportSkills: +class TestDeployRelease: """ - Test Class for export_skills + Test Class for deploy_release """ @responses.activate - def test_export_skills_all_params(self): + def test_deploy_release_all_params(self): """ - export_skills() + deploy_release() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_export') - mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', @@ -2865,11 +3570,15 @@ def test_export_skills_all_params(self): # Set up parameter values assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' include_audit = False # Invoke method - response = _service.export_skills( + response = _service.deploy_release( assistant_id, + release, + environment_id, include_audit=include_audit, headers={}, ) @@ -2881,26 +3590,29 @@ def test_export_skills_all_params(self): query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['environment_id'] == 'testString' - def test_export_skills_all_params_with_retries(self): - # Enable retries and run test_export_skills_all_params. + def test_deploy_release_all_params_with_retries(self): + # Enable retries and run test_deploy_release_all_params. _service.enable_retries() - self.test_export_skills_all_params() + self.test_deploy_release_all_params() - # Disable retries and run test_export_skills_all_params. + # Disable retries and run test_deploy_release_all_params. _service.disable_retries() - self.test_export_skills_all_params() + self.test_deploy_release_all_params() @responses.activate - def test_export_skills_required_params(self): + def test_deploy_release_required_params(self): """ - test_export_skills_required_params() + test_deploy_release_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_export') - mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', @@ -2909,36 +3621,43 @@ def test_export_skills_required_params(self): # Set up parameter values assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' # Invoke method - response = _service.export_skills( + response = _service.deploy_release( assistant_id, + release, + environment_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['environment_id'] == 'testString' - def test_export_skills_required_params_with_retries(self): - # Enable retries and run test_export_skills_required_params. + def test_deploy_release_required_params_with_retries(self): + # Enable retries and run test_deploy_release_required_params. _service.enable_retries() - self.test_export_skills_required_params() + self.test_deploy_release_required_params() - # Disable retries and run test_export_skills_required_params. + # Disable retries and run test_deploy_release_required_params. _service.disable_retries() - self.test_export_skills_required_params() + self.test_deploy_release_required_params() @responses.activate - def test_export_skills_value_error(self): + def test_deploy_release_value_error(self): """ - test_export_skills_value_error() + test_deploy_release_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_export') - mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', @@ -2947,334 +3666,174 @@ def test_export_skills_value_error(self): # Set up parameter values assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "release": release, + "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.export_skills(**req_copy) + _service.deploy_release(**req_copy) - def test_export_skills_value_error_with_retries(self): - # Enable retries and run test_export_skills_value_error. + def test_deploy_release_value_error_with_retries(self): + # Enable retries and run test_deploy_release_value_error. _service.enable_retries() - self.test_export_skills_value_error() + self.test_deploy_release_value_error() - # Disable retries and run test_export_skills_value_error. + # Disable retries and run test_deploy_release_value_error. _service.disable_retries() - self.test_export_skills_value_error() + self.test_deploy_release_value_error() -class TestImportSkills: +class TestCreateReleaseExport: """ - Test Class for import_skills + Test Class for create_release_export """ @responses.activate - def test_import_skills_all_params(self): + def test_create_release_export_all_params(self): """ - import_skills() + create_release_export() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_import') - mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' responses.add( responses.POST, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) - # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model = {} - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + include_audit = False - # Construct a dict representation of a SearchSettingsDiscovery model - search_settings_discovery_model = {} - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - # Construct a dict representation of a SearchSettingsMessages model - search_settings_messages_model = {} - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - # Construct a dict representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model = {} - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - # Construct a dict representation of a SearchSettings model - search_settings_model = {} - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - - # Construct a dict representation of a SkillImport model - skill_import_model = {} - skill_import_model['name'] = 'testString' - skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'anyKey': 'anyValue'} - skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} - skill_import_model['search_settings'] = search_settings_model - skill_import_model['language'] = 'testString' - skill_import_model['type'] = 'action' - - # Construct a dict representation of a AssistantState model - assistant_state_model = {} - assistant_state_model['action_disabled'] = True - assistant_state_model['dialog_disabled'] = True - - # Set up parameter values - assistant_id = 'testString' - assistant_skills = [skill_import_model] - assistant_state = assistant_state_model - include_audit = False - - # Invoke method - response = _service.import_skills( - assistant_id, - assistant_skills, - assistant_state, - include_audit=include_audit, - headers={}, - ) + # Invoke method + response = _service.create_release_export( + assistant_id, + release, + include_audit=include_audit, + headers={}, + ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 + assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['assistant_skills'] == [skill_import_model] - assert req_body['assistant_state'] == assistant_state_model - def test_import_skills_all_params_with_retries(self): - # Enable retries and run test_import_skills_all_params. + def test_create_release_export_all_params_with_retries(self): + # Enable retries and run test_create_release_export_all_params. _service.enable_retries() - self.test_import_skills_all_params() + self.test_create_release_export_all_params() - # Disable retries and run test_import_skills_all_params. + # Disable retries and run test_create_release_export_all_params. _service.disable_retries() - self.test_import_skills_all_params() + self.test_create_release_export_all_params() @responses.activate - def test_import_skills_required_params(self): + def test_create_release_export_required_params(self): """ - test_import_skills_required_params() + test_create_release_export_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_import') - mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' responses.add( responses.POST, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) - # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model = {} - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - # Construct a dict representation of a SearchSettingsDiscovery model - search_settings_discovery_model = {} - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - # Construct a dict representation of a SearchSettingsMessages model - search_settings_messages_model = {} - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - # Construct a dict representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model = {} - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - # Construct a dict representation of a SearchSettings model - search_settings_model = {} - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - - # Construct a dict representation of a SkillImport model - skill_import_model = {} - skill_import_model['name'] = 'testString' - skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'anyKey': 'anyValue'} - skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} - skill_import_model['search_settings'] = search_settings_model - skill_import_model['language'] = 'testString' - skill_import_model['type'] = 'action' - - # Construct a dict representation of a AssistantState model - assistant_state_model = {} - assistant_state_model['action_disabled'] = True - assistant_state_model['dialog_disabled'] = True - # Set up parameter values assistant_id = 'testString' - assistant_skills = [skill_import_model] - assistant_state = assistant_state_model + release = 'testString' # Invoke method - response = _service.import_skills( + response = _service.create_release_export( assistant_id, - assistant_skills, - assistant_state, + release, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['assistant_skills'] == [skill_import_model] - assert req_body['assistant_state'] == assistant_state_model + assert response.status_code == 200 - def test_import_skills_required_params_with_retries(self): - # Enable retries and run test_import_skills_required_params. + def test_create_release_export_required_params_with_retries(self): + # Enable retries and run test_create_release_export_required_params. _service.enable_retries() - self.test_import_skills_required_params() + self.test_create_release_export_required_params() - # Disable retries and run test_import_skills_required_params. + # Disable retries and run test_create_release_export_required_params. _service.disable_retries() - self.test_import_skills_required_params() + self.test_create_release_export_required_params() @responses.activate - def test_import_skills_value_error(self): + def test_create_release_export_value_error(self): """ - test_import_skills_value_error() + test_create_release_export_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_import') - mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' responses.add( responses.POST, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) - # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model = {} - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - # Construct a dict representation of a SearchSettingsDiscovery model - search_settings_discovery_model = {} - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - # Construct a dict representation of a SearchSettingsMessages model - search_settings_messages_model = {} - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - # Construct a dict representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model = {} - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - # Construct a dict representation of a SearchSettings model - search_settings_model = {} - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - - # Construct a dict representation of a SkillImport model - skill_import_model = {} - skill_import_model['name'] = 'testString' - skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'anyKey': 'anyValue'} - skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} - skill_import_model['search_settings'] = search_settings_model - skill_import_model['language'] = 'testString' - skill_import_model['type'] = 'action' - - # Construct a dict representation of a AssistantState model - assistant_state_model = {} - assistant_state_model['action_disabled'] = True - assistant_state_model['dialog_disabled'] = True - # Set up parameter values assistant_id = 'testString' - assistant_skills = [skill_import_model] - assistant_state = assistant_state_model + release = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "assistant_skills": assistant_skills, - "assistant_state": assistant_state, + "release": release, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.import_skills(**req_copy) + _service.create_release_export(**req_copy) - def test_import_skills_value_error_with_retries(self): - # Enable retries and run test_import_skills_value_error. + def test_create_release_export_value_error_with_retries(self): + # Enable retries and run test_create_release_export_value_error. _service.enable_retries() - self.test_import_skills_value_error() + self.test_create_release_export_value_error() - # Disable retries and run test_import_skills_value_error. + # Disable retries and run test_create_release_export_value_error. _service.disable_retries() - self.test_import_skills_value_error() + self.test_create_release_export_value_error() -class TestImportSkillsStatus: +class TestDownloadReleaseExport: """ - Test Class for import_skills_status + Test Class for download_release_export """ @responses.activate - def test_import_skills_status_all_params(self): + def test_download_release_export_all_params(self): """ - import_skills_status() + download_release_export() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_import/status') - mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' responses.add( responses.GET, url, @@ -3285,34 +3844,84 @@ def test_import_skills_status_all_params(self): # Set up parameter values assistant_id = 'testString' + release = 'testString' + accept = 'application/json' + include_audit = False # Invoke method - response = _service.import_skills_status( + response = _service.download_release_export( assistant_id, + release, + accept=accept, + include_audit=include_audit, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - def test_import_skills_status_all_params_with_retries(self): - # Enable retries and run test_import_skills_status_all_params. + def test_download_release_export_all_params_with_retries(self): + # Enable retries and run test_download_release_export_all_params. _service.enable_retries() - self.test_import_skills_status_all_params() + self.test_download_release_export_all_params() - # Disable retries and run test_import_skills_status_all_params. + # Disable retries and run test_download_release_export_all_params. _service.disable_retries() - self.test_import_skills_status_all_params() + self.test_download_release_export_all_params() @responses.activate - def test_import_skills_status_value_error(self): + def test_download_release_export_required_params(self): """ - test_import_skills_status_value_error() + test_download_release_export_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_import/status') - mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + + # Invoke method + response = _service.download_release_export( + assistant_id, + release, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_download_release_export_required_params_with_retries(self): + # Enable retries and run test_download_release_export_required_params. + _service.enable_retries() + self.test_download_release_export_required_params() + + # Disable retries and run test_download_release_export_required_params. + _service.disable_retries() + self.test_download_release_export_required_params() + + @responses.activate + def test_download_release_export_value_error(self): + """ + test_download_release_export_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' responses.add( responses.GET, url, @@ -3323,282 +3932,2342 @@ def test_import_skills_status_value_error(self): # Set up parameter values assistant_id = 'testString' + release = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "release": release, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.import_skills_status(**req_copy) + _service.download_release_export(**req_copy) - def test_import_skills_status_value_error_with_retries(self): - # Enable retries and run test_import_skills_status_value_error. + def test_download_release_export_value_error_with_retries(self): + # Enable retries and run test_download_release_export_value_error. _service.enable_retries() - self.test_import_skills_status_value_error() + self.test_download_release_export_value_error() - # Disable retries and run test_import_skills_status_value_error. + # Disable retries and run test_download_release_export_value_error. _service.disable_retries() - self.test_import_skills_status_value_error() - - -# endregion -############################################################################## -# End of Service: Skills -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region + self.test_download_release_export_value_error() -class TestModel_AgentAvailabilityMessage: +class TestCreateReleaseImport: """ - Test Class for AgentAvailabilityMessage + Test Class for create_release_import """ - def test_agent_availability_message_serialization(self): + @responses.activate + def test_create_release_import_all_params(self): """ - Test serialization/deserialization for AgentAvailabilityMessage + create_release_import() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Failed", "task_id": "task_id", "assistant_id": "assistant_id", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) - # Construct a json representation of a AgentAvailabilityMessage model - agent_availability_message_model_json = {} - agent_availability_message_model_json['message'] = 'testString' - - # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation - agent_availability_message_model = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json) - assert agent_availability_message_model != False - - # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation - agent_availability_message_model_dict = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json).__dict__ - agent_availability_message_model2 = AgentAvailabilityMessage(**agent_availability_message_model_dict) + # Set up parameter values + assistant_id = 'testString' + body = io.BytesIO(b'This is a mock file.').getvalue() + include_audit = False - # Verify the model instances are equivalent - assert agent_availability_message_model == agent_availability_message_model2 + # Invoke method + response = _service.create_release_import( + assistant_id, + body, + include_audit=include_audit, + headers={}, + ) - # Convert model instance back to dict and verify no loss of data - agent_availability_message_model_json2 = agent_availability_message_model.to_dict() - assert agent_availability_message_model_json2 == agent_availability_message_model_json + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + assert responses.calls[0].request.body == body + def test_create_release_import_all_params_with_retries(self): + # Enable retries and run test_create_release_import_all_params. + _service.enable_retries() + self.test_create_release_import_all_params() -class TestModel_AssistantCollection: - """ - Test Class for AssistantCollection - """ + # Disable retries and run test_create_release_import_all_params. + _service.disable_retries() + self.test_create_release_import_all_params() - def test_assistant_collection_serialization(self): + @responses.activate + def test_create_release_import_required_params(self): """ - Test serialization/deserialization for AssistantCollection + test_create_release_import_required_params() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Failed", "task_id": "task_id", "assistant_id": "assistant_id", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) - # Construct dict forms of any model objects needed in order to build this model. - - assistant_data_model = {} # AssistantData - assistant_data_model['name'] = 'testString' - assistant_data_model['description'] = 'testString' - assistant_data_model['language'] = 'testString' - - pagination_model = {} # Pagination - pagination_model['refresh_url'] = 'testString' - pagination_model['next_url'] = 'testString' - pagination_model['total'] = 38 - pagination_model['matched'] = 38 - pagination_model['refresh_cursor'] = 'testString' - pagination_model['next_cursor'] = 'testString' - - # Construct a json representation of a AssistantCollection model - assistant_collection_model_json = {} - assistant_collection_model_json['assistants'] = [assistant_data_model] - assistant_collection_model_json['pagination'] = pagination_model - - # Construct a model instance of AssistantCollection by calling from_dict on the json representation - assistant_collection_model = AssistantCollection.from_dict(assistant_collection_model_json) - assert assistant_collection_model != False - - # Construct a model instance of AssistantCollection by calling from_dict on the json representation - assistant_collection_model_dict = AssistantCollection.from_dict(assistant_collection_model_json).__dict__ - assistant_collection_model2 = AssistantCollection(**assistant_collection_model_dict) + # Set up parameter values + assistant_id = 'testString' + body = io.BytesIO(b'This is a mock file.').getvalue() - # Verify the model instances are equivalent - assert assistant_collection_model == assistant_collection_model2 + # Invoke method + response = _service.create_release_import( + assistant_id, + body, + headers={}, + ) - # Convert model instance back to dict and verify no loss of data - assistant_collection_model_json2 = assistant_collection_model.to_dict() - assert assistant_collection_model_json2 == assistant_collection_model_json + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + assert responses.calls[0].request.body == body + def test_create_release_import_required_params_with_retries(self): + # Enable retries and run test_create_release_import_required_params. + _service.enable_retries() + self.test_create_release_import_required_params() -class TestModel_AssistantData: - """ - Test Class for AssistantData - """ + # Disable retries and run test_create_release_import_required_params. + _service.disable_retries() + self.test_create_release_import_required_params() - def test_assistant_data_serialization(self): + @responses.activate + def test_create_release_import_value_error(self): """ - Test serialization/deserialization for AssistantData + test_create_release_import_value_error() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Failed", "task_id": "task_id", "assistant_id": "assistant_id", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) - # Construct a json representation of a AssistantData model - assistant_data_model_json = {} - assistant_data_model_json['name'] = 'testString' - assistant_data_model_json['description'] = 'testString' - assistant_data_model_json['language'] = 'testString' - - # Construct a model instance of AssistantData by calling from_dict on the json representation - assistant_data_model = AssistantData.from_dict(assistant_data_model_json) - assert assistant_data_model != False + # Set up parameter values + assistant_id = 'testString' + body = io.BytesIO(b'This is a mock file.').getvalue() - # Construct a model instance of AssistantData by calling from_dict on the json representation - assistant_data_model_dict = AssistantData.from_dict(assistant_data_model_json).__dict__ - assistant_data_model2 = AssistantData(**assistant_data_model_dict) + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "body": body, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_release_import(**req_copy) - # Verify the model instances are equivalent - assert assistant_data_model == assistant_data_model2 + def test_create_release_import_value_error_with_retries(self): + # Enable retries and run test_create_release_import_value_error. + _service.enable_retries() + self.test_create_release_import_value_error() - # Convert model instance back to dict and verify no loss of data - assistant_data_model_json2 = assistant_data_model.to_dict() - assert assistant_data_model_json2 == assistant_data_model_json + # Disable retries and run test_create_release_import_value_error. + _service.disable_retries() + self.test_create_release_import_value_error() -class TestModel_AssistantSkill: +class TestGetReleaseImportStatus: """ - Test Class for AssistantSkill + Test Class for get_release_import_status """ - def test_assistant_skill_serialization(self): + @responses.activate + def test_get_release_import_status_all_params(self): """ - Test serialization/deserialization for AssistantSkill + get_release_import_status() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Completed", "task_id": "task_id", "assistant_id": "assistant_id", "status_errors": [{"message": "message"}], "status_description": "status_description", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) - # Construct a json representation of a AssistantSkill model - assistant_skill_model_json = {} - assistant_skill_model_json['skill_id'] = 'testString' - assistant_skill_model_json['type'] = 'dialog' - - # Construct a model instance of AssistantSkill by calling from_dict on the json representation - assistant_skill_model = AssistantSkill.from_dict(assistant_skill_model_json) - assert assistant_skill_model != False - - # Construct a model instance of AssistantSkill by calling from_dict on the json representation - assistant_skill_model_dict = AssistantSkill.from_dict(assistant_skill_model_json).__dict__ - assistant_skill_model2 = AssistantSkill(**assistant_skill_model_dict) + # Set up parameter values + assistant_id = 'testString' + include_audit = False - # Verify the model instances are equivalent - assert assistant_skill_model == assistant_skill_model2 + # Invoke method + response = _service.get_release_import_status( + assistant_id, + include_audit=include_audit, + headers={}, + ) - # Convert model instance back to dict and verify no loss of data - assistant_skill_model_json2 = assistant_skill_model.to_dict() - assert assistant_skill_model_json2 == assistant_skill_model_json + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_get_release_import_status_all_params_with_retries(self): + # Enable retries and run test_get_release_import_status_all_params. + _service.enable_retries() + self.test_get_release_import_status_all_params() -class TestModel_AssistantState: - """ - Test Class for AssistantState - """ + # Disable retries and run test_get_release_import_status_all_params. + _service.disable_retries() + self.test_get_release_import_status_all_params() - def test_assistant_state_serialization(self): + @responses.activate + def test_get_release_import_status_required_params(self): """ - Test serialization/deserialization for AssistantState + test_get_release_import_status_required_params() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Completed", "task_id": "task_id", "assistant_id": "assistant_id", "status_errors": [{"message": "message"}], "status_description": "status_description", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) - # Construct a json representation of a AssistantState model - assistant_state_model_json = {} - assistant_state_model_json['action_disabled'] = True - assistant_state_model_json['dialog_disabled'] = True - - # Construct a model instance of AssistantState by calling from_dict on the json representation - assistant_state_model = AssistantState.from_dict(assistant_state_model_json) - assert assistant_state_model != False + # Set up parameter values + assistant_id = 'testString' - # Construct a model instance of AssistantState by calling from_dict on the json representation - assistant_state_model_dict = AssistantState.from_dict(assistant_state_model_json).__dict__ - assistant_state_model2 = AssistantState(**assistant_state_model_dict) + # Invoke method + response = _service.get_release_import_status( + assistant_id, + headers={}, + ) - # Verify the model instances are equivalent - assert assistant_state_model == assistant_state_model2 + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - # Convert model instance back to dict and verify no loss of data - assistant_state_model_json2 = assistant_state_model.to_dict() - assert assistant_state_model_json2 == assistant_state_model_json + def test_get_release_import_status_required_params_with_retries(self): + # Enable retries and run test_get_release_import_status_required_params. + _service.enable_retries() + self.test_get_release_import_status_required_params() + # Disable retries and run test_get_release_import_status_required_params. + _service.disable_retries() + self.test_get_release_import_status_required_params() -class TestModel_BaseEnvironmentOrchestration: - """ + @responses.activate + def test_get_release_import_status_value_error(self): + """ + test_get_release_import_status_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Completed", "task_id": "task_id", "assistant_id": "assistant_id", "status_errors": [{"message": "message"}], "status_description": "status_description", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_release_import_status(**req_copy) + + def test_get_release_import_status_value_error_with_retries(self): + # Enable retries and run test_get_release_import_status_value_error. + _service.enable_retries() + self.test_get_release_import_status_value_error() + + # Disable retries and run test_get_release_import_status_value_error. + _service.disable_retries() + self.test_get_release_import_status_value_error() + + +# endregion +############################################################################## +# End of Service: Releases +############################################################################## + +############################################################################## +# Start of Service: Skills +############################################################################## +# region + + +class TestGetSkill: + """ + Test Class for get_skill + """ + + @responses.activate + def test_get_skill_all_params(self): + """ + get_skill() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + + # Invoke method + response = _service.get_skill( + assistant_id, + skill_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_skill_all_params_with_retries(self): + # Enable retries and run test_get_skill_all_params. + _service.enable_retries() + self.test_get_skill_all_params() + + # Disable retries and run test_get_skill_all_params. + _service.disable_retries() + self.test_get_skill_all_params() + + @responses.activate + def test_get_skill_value_error(self): + """ + test_get_skill_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "skill_id": skill_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_skill(**req_copy) + + def test_get_skill_value_error_with_retries(self): + # Enable retries and run test_get_skill_value_error. + _service.enable_retries() + self.test_get_skill_value_error() + + # Disable retries and run test_get_skill_value_error. + _service.disable_retries() + self.test_get_skill_value_error() + + +class TestUpdateSkill: + """ + Test Class for update_skill + """ + + @responses.activate + def test_update_skill_all_params(self): + """ + update_skill() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model = {} + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + # Construct a dict representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model = {} + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + # Construct a dict representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model = {} + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a dict representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model = {} + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a dict representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model = {} + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + # Construct a dict representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model = {} + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + name = 'testString' + description = 'testString' + workspace = {'anyKey': 'anyValue'} + dialog_settings = {'anyKey': 'anyValue'} + search_settings = search_settings_model + + # Invoke method + response = _service.update_skill( + assistant_id, + skill_id, + name=name, + description=description, + workspace=workspace, + dialog_settings=dialog_settings, + search_settings=search_settings, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['workspace'] == {'anyKey': 'anyValue'} + assert req_body['dialog_settings'] == {'anyKey': 'anyValue'} + assert req_body['search_settings'] == search_settings_model + + def test_update_skill_all_params_with_retries(self): + # Enable retries and run test_update_skill_all_params. + _service.enable_retries() + self.test_update_skill_all_params() + + # Disable retries and run test_update_skill_all_params. + _service.disable_retries() + self.test_update_skill_all_params() + + @responses.activate + def test_update_skill_value_error(self): + """ + test_update_skill_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model = {} + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + # Construct a dict representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model = {} + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + # Construct a dict representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model = {} + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a dict representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model = {} + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a dict representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model = {} + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + # Construct a dict representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model = {} + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + name = 'testString' + description = 'testString' + workspace = {'anyKey': 'anyValue'} + dialog_settings = {'anyKey': 'anyValue'} + search_settings = search_settings_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "skill_id": skill_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_skill(**req_copy) + + def test_update_skill_value_error_with_retries(self): + # Enable retries and run test_update_skill_value_error. + _service.enable_retries() + self.test_update_skill_value_error() + + # Disable retries and run test_update_skill_value_error. + _service.disable_retries() + self.test_update_skill_value_error() + + +class TestExportSkills: + """ + Test Class for export_skills + """ + + @responses.activate + def test_export_skills_all_params(self): + """ + export_skills() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + include_audit = False + + # Invoke method + response = _service.export_skills( + assistant_id, + include_audit=include_audit, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_export_skills_all_params_with_retries(self): + # Enable retries and run test_export_skills_all_params. + _service.enable_retries() + self.test_export_skills_all_params() + + # Disable retries and run test_export_skills_all_params. + _service.disable_retries() + self.test_export_skills_all_params() + + @responses.activate + def test_export_skills_required_params(self): + """ + test_export_skills_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.export_skills( + assistant_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_export_skills_required_params_with_retries(self): + # Enable retries and run test_export_skills_required_params. + _service.enable_retries() + self.test_export_skills_required_params() + + # Disable retries and run test_export_skills_required_params. + _service.disable_retries() + self.test_export_skills_required_params() + + @responses.activate + def test_export_skills_value_error(self): + """ + test_export_skills_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.export_skills(**req_copy) + + def test_export_skills_value_error_with_retries(self): + # Enable retries and run test_export_skills_value_error. + _service.enable_retries() + self.test_export_skills_value_error() + + # Disable retries and run test_export_skills_value_error. + _service.disable_retries() + self.test_export_skills_value_error() + + +class TestImportSkills: + """ + Test Class for import_skills + """ + + @responses.activate + def test_import_skills_all_params(self): + """ + import_skills() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model = {} + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + # Construct a dict representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model = {} + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + # Construct a dict representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model = {} + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a dict representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model = {} + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a dict representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model = {} + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + # Construct a dict representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model = {} + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} + skill_import_model['search_settings'] = search_settings_model + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + include_audit = False + + # Invoke method + response = _service.import_skills( + assistant_id, + assistant_skills, + assistant_state, + include_audit=include_audit, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['assistant_skills'] == [skill_import_model] + assert req_body['assistant_state'] == assistant_state_model + + def test_import_skills_all_params_with_retries(self): + # Enable retries and run test_import_skills_all_params. + _service.enable_retries() + self.test_import_skills_all_params() + + # Disable retries and run test_import_skills_all_params. + _service.disable_retries() + self.test_import_skills_all_params() + + @responses.activate + def test_import_skills_required_params(self): + """ + test_import_skills_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model = {} + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + # Construct a dict representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model = {} + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + # Construct a dict representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model = {} + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a dict representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model = {} + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a dict representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model = {} + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + # Construct a dict representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model = {} + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} + skill_import_model['search_settings'] = search_settings_model + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + + # Invoke method + response = _service.import_skills( + assistant_id, + assistant_skills, + assistant_state, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['assistant_skills'] == [skill_import_model] + assert req_body['assistant_state'] == assistant_state_model + + def test_import_skills_required_params_with_retries(self): + # Enable retries and run test_import_skills_required_params. + _service.enable_retries() + self.test_import_skills_required_params() + + # Disable retries and run test_import_skills_required_params. + _service.disable_retries() + self.test_import_skills_required_params() + + @responses.activate + def test_import_skills_value_error(self): + """ + test_import_skills_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model = {} + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + # Construct a dict representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model = {} + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + # Construct a dict representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model = {} + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a dict representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model = {} + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a dict representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model = {} + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + # Construct a dict representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model = {} + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} + skill_import_model['search_settings'] = search_settings_model + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "assistant_skills": assistant_skills, + "assistant_state": assistant_state, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.import_skills(**req_copy) + + def test_import_skills_value_error_with_retries(self): + # Enable retries and run test_import_skills_value_error. + _service.enable_retries() + self.test_import_skills_value_error() + + # Disable retries and run test_import_skills_value_error. + _service.disable_retries() + self.test_import_skills_value_error() + + +class TestImportSkillsStatus: + """ + Test Class for import_skills_status + """ + + @responses.activate + def test_import_skills_status_all_params(self): + """ + import_skills_status() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import/status') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.import_skills_status( + assistant_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_import_skills_status_all_params_with_retries(self): + # Enable retries and run test_import_skills_status_all_params. + _service.enable_retries() + self.test_import_skills_status_all_params() + + # Disable retries and run test_import_skills_status_all_params. + _service.disable_retries() + self.test_import_skills_status_all_params() + + @responses.activate + def test_import_skills_status_value_error(self): + """ + test_import_skills_status_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import/status') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.import_skills_status(**req_copy) + + def test_import_skills_status_value_error_with_retries(self): + # Enable retries and run test_import_skills_status_value_error. + _service.enable_retries() + self.test_import_skills_status_value_error() + + # Disable retries and run test_import_skills_status_value_error. + _service.disable_retries() + self.test_import_skills_status_value_error() + + +# endregion +############################################################################## +# End of Service: Skills +############################################################################## + + +############################################################################## +# Start of Model Tests +############################################################################## +# region + + +class TestModel_AgentAvailabilityMessage: + """ + Test Class for AgentAvailabilityMessage + """ + + def test_agent_availability_message_serialization(self): + """ + Test serialization/deserialization for AgentAvailabilityMessage + """ + + # Construct a json representation of a AgentAvailabilityMessage model + agent_availability_message_model_json = {} + agent_availability_message_model_json['message'] = 'testString' + + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json) + assert agent_availability_message_model != False + + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model_dict = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json).__dict__ + agent_availability_message_model2 = AgentAvailabilityMessage(**agent_availability_message_model_dict) + + # Verify the model instances are equivalent + assert agent_availability_message_model == agent_availability_message_model2 + + # Convert model instance back to dict and verify no loss of data + agent_availability_message_model_json2 = agent_availability_message_model.to_dict() + assert agent_availability_message_model_json2 == agent_availability_message_model_json + + +class TestModel_AssistantCollection: + """ + Test Class for AssistantCollection + """ + + def test_assistant_collection_serialization(self): + """ + Test serialization/deserialization for AssistantCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + assistant_data_model = {} # AssistantData + assistant_data_model['name'] = 'testString' + assistant_data_model['description'] = 'testString' + assistant_data_model['language'] = 'testString' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a AssistantCollection model + assistant_collection_model_json = {} + assistant_collection_model_json['assistants'] = [assistant_data_model] + assistant_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of AssistantCollection by calling from_dict on the json representation + assistant_collection_model = AssistantCollection.from_dict(assistant_collection_model_json) + assert assistant_collection_model != False + + # Construct a model instance of AssistantCollection by calling from_dict on the json representation + assistant_collection_model_dict = AssistantCollection.from_dict(assistant_collection_model_json).__dict__ + assistant_collection_model2 = AssistantCollection(**assistant_collection_model_dict) + + # Verify the model instances are equivalent + assert assistant_collection_model == assistant_collection_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_collection_model_json2 = assistant_collection_model.to_dict() + assert assistant_collection_model_json2 == assistant_collection_model_json + + +class TestModel_AssistantData: + """ + Test Class for AssistantData + """ + + def test_assistant_data_serialization(self): + """ + Test serialization/deserialization for AssistantData + """ + + # Construct a json representation of a AssistantData model + assistant_data_model_json = {} + assistant_data_model_json['name'] = 'testString' + assistant_data_model_json['description'] = 'testString' + assistant_data_model_json['language'] = 'testString' + + # Construct a model instance of AssistantData by calling from_dict on the json representation + assistant_data_model = AssistantData.from_dict(assistant_data_model_json) + assert assistant_data_model != False + + # Construct a model instance of AssistantData by calling from_dict on the json representation + assistant_data_model_dict = AssistantData.from_dict(assistant_data_model_json).__dict__ + assistant_data_model2 = AssistantData(**assistant_data_model_dict) + + # Verify the model instances are equivalent + assert assistant_data_model == assistant_data_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_data_model_json2 = assistant_data_model.to_dict() + assert assistant_data_model_json2 == assistant_data_model_json + + +class TestModel_AssistantSkill: + """ + Test Class for AssistantSkill + """ + + def test_assistant_skill_serialization(self): + """ + Test serialization/deserialization for AssistantSkill + """ + + # Construct a json representation of a AssistantSkill model + assistant_skill_model_json = {} + assistant_skill_model_json['skill_id'] = 'testString' + assistant_skill_model_json['type'] = 'dialog' + + # Construct a model instance of AssistantSkill by calling from_dict on the json representation + assistant_skill_model = AssistantSkill.from_dict(assistant_skill_model_json) + assert assistant_skill_model != False + + # Construct a model instance of AssistantSkill by calling from_dict on the json representation + assistant_skill_model_dict = AssistantSkill.from_dict(assistant_skill_model_json).__dict__ + assistant_skill_model2 = AssistantSkill(**assistant_skill_model_dict) + + # Verify the model instances are equivalent + assert assistant_skill_model == assistant_skill_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_skill_model_json2 = assistant_skill_model.to_dict() + assert assistant_skill_model_json2 == assistant_skill_model_json + + +class TestModel_AssistantState: + """ + Test Class for AssistantState + """ + + def test_assistant_state_serialization(self): + """ + Test serialization/deserialization for AssistantState + """ + + # Construct a json representation of a AssistantState model + assistant_state_model_json = {} + assistant_state_model_json['action_disabled'] = True + assistant_state_model_json['dialog_disabled'] = True + + # Construct a model instance of AssistantState by calling from_dict on the json representation + assistant_state_model = AssistantState.from_dict(assistant_state_model_json) + assert assistant_state_model != False + + # Construct a model instance of AssistantState by calling from_dict on the json representation + assistant_state_model_dict = AssistantState.from_dict(assistant_state_model_json).__dict__ + assistant_state_model2 = AssistantState(**assistant_state_model_dict) + + # Verify the model instances are equivalent + assert assistant_state_model == assistant_state_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_state_model_json2 = assistant_state_model.to_dict() + assert assistant_state_model_json2 == assistant_state_model_json + + +class TestModel_BaseEnvironmentOrchestration: + """ Test Class for BaseEnvironmentOrchestration """ - def test_base_environment_orchestration_serialization(self): + def test_base_environment_orchestration_serialization(self): + """ + Test serialization/deserialization for BaseEnvironmentOrchestration + """ + + # Construct a json representation of a BaseEnvironmentOrchestration model + base_environment_orchestration_model_json = {} + base_environment_orchestration_model_json['search_skill_fallback'] = True + + # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation + base_environment_orchestration_model = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json) + assert base_environment_orchestration_model != False + + # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation + base_environment_orchestration_model_dict = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json).__dict__ + base_environment_orchestration_model2 = BaseEnvironmentOrchestration(**base_environment_orchestration_model_dict) + + # Verify the model instances are equivalent + assert base_environment_orchestration_model == base_environment_orchestration_model2 + + # Convert model instance back to dict and verify no loss of data + base_environment_orchestration_model_json2 = base_environment_orchestration_model.to_dict() + assert base_environment_orchestration_model_json2 == base_environment_orchestration_model_json + + +class TestModel_BaseEnvironmentReleaseReference: + """ + Test Class for BaseEnvironmentReleaseReference + """ + + def test_base_environment_release_reference_serialization(self): + """ + Test serialization/deserialization for BaseEnvironmentReleaseReference + """ + + # Construct a json representation of a BaseEnvironmentReleaseReference model + base_environment_release_reference_model_json = {} + base_environment_release_reference_model_json['release'] = 'testString' + + # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation + base_environment_release_reference_model = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json) + assert base_environment_release_reference_model != False + + # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation + base_environment_release_reference_model_dict = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json).__dict__ + base_environment_release_reference_model2 = BaseEnvironmentReleaseReference(**base_environment_release_reference_model_dict) + + # Verify the model instances are equivalent + assert base_environment_release_reference_model == base_environment_release_reference_model2 + + # Convert model instance back to dict and verify no loss of data + base_environment_release_reference_model_json2 = base_environment_release_reference_model.to_dict() + assert base_environment_release_reference_model_json2 == base_environment_release_reference_model_json + + +class TestModel_BulkClassifyOutput: + """ + Test Class for BulkClassifyOutput + """ + + def test_bulk_classify_output_serialization(self): + """ + Test serialization/deserialization for BulkClassifyOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + # Construct a json representation of a BulkClassifyOutput model + bulk_classify_output_model_json = {} + bulk_classify_output_model_json['input'] = bulk_classify_utterance_model + bulk_classify_output_model_json['entities'] = [runtime_entity_model] + bulk_classify_output_model_json['intents'] = [runtime_intent_model] + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model = BulkClassifyOutput.from_dict(bulk_classify_output_model_json) + assert bulk_classify_output_model != False + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model_dict = BulkClassifyOutput.from_dict(bulk_classify_output_model_json).__dict__ + bulk_classify_output_model2 = BulkClassifyOutput(**bulk_classify_output_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_output_model == bulk_classify_output_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() + assert bulk_classify_output_model_json2 == bulk_classify_output_model_json + + +class TestModel_BulkClassifyResponse: + """ + Test Class for BulkClassifyResponse + """ + + def test_bulk_classify_response_serialization(self): + """ + Test serialization/deserialization for BulkClassifyResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + bulk_classify_output_model = {} # BulkClassifyOutput + bulk_classify_output_model['input'] = bulk_classify_utterance_model + bulk_classify_output_model['entities'] = [runtime_entity_model] + bulk_classify_output_model['intents'] = [runtime_intent_model] + + # Construct a json representation of a BulkClassifyResponse model + bulk_classify_response_model_json = {} + bulk_classify_response_model_json['output'] = [bulk_classify_output_model] + + # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation + bulk_classify_response_model = BulkClassifyResponse.from_dict(bulk_classify_response_model_json) + assert bulk_classify_response_model != False + + # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation + bulk_classify_response_model_dict = BulkClassifyResponse.from_dict(bulk_classify_response_model_json).__dict__ + bulk_classify_response_model2 = BulkClassifyResponse(**bulk_classify_response_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_response_model == bulk_classify_response_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() + assert bulk_classify_response_model_json2 == bulk_classify_response_model_json + + +class TestModel_BulkClassifyUtterance: + """ + Test Class for BulkClassifyUtterance + """ + + def test_bulk_classify_utterance_serialization(self): + """ + Test serialization/deserialization for BulkClassifyUtterance + """ + + # Construct a json representation of a BulkClassifyUtterance model + bulk_classify_utterance_model_json = {} + bulk_classify_utterance_model_json['text'] = 'testString' + + # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation + bulk_classify_utterance_model = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json) + assert bulk_classify_utterance_model != False + + # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation + bulk_classify_utterance_model_dict = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json).__dict__ + bulk_classify_utterance_model2 = BulkClassifyUtterance(**bulk_classify_utterance_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_utterance_model == bulk_classify_utterance_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() + assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json + + +class TestModel_CaptureGroup: + """ + Test Class for CaptureGroup + """ + + def test_capture_group_serialization(self): + """ + Test serialization/deserialization for CaptureGroup + """ + + # Construct a json representation of a CaptureGroup model + capture_group_model_json = {} + capture_group_model_json['group'] = 'testString' + capture_group_model_json['location'] = [38] + + # Construct a model instance of CaptureGroup by calling from_dict on the json representation + capture_group_model = CaptureGroup.from_dict(capture_group_model_json) + assert capture_group_model != False + + # Construct a model instance of CaptureGroup by calling from_dict on the json representation + capture_group_model_dict = CaptureGroup.from_dict(capture_group_model_json).__dict__ + capture_group_model2 = CaptureGroup(**capture_group_model_dict) + + # Verify the model instances are equivalent + assert capture_group_model == capture_group_model2 + + # Convert model instance back to dict and verify no loss of data + capture_group_model_json2 = capture_group_model.to_dict() + assert capture_group_model_json2 == capture_group_model_json + + +class TestModel_ChannelTransferInfo: + """ + Test Class for ChannelTransferInfo + """ + + def test_channel_transfer_info_serialization(self): + """ + Test serialization/deserialization for ChannelTransferInfo + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a json representation of a ChannelTransferInfo model + channel_transfer_info_model_json = {} + channel_transfer_info_model_json['target'] = channel_transfer_target_model + + # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation + channel_transfer_info_model = ChannelTransferInfo.from_dict(channel_transfer_info_model_json) + assert channel_transfer_info_model != False + + # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation + channel_transfer_info_model_dict = ChannelTransferInfo.from_dict(channel_transfer_info_model_json).__dict__ + channel_transfer_info_model2 = ChannelTransferInfo(**channel_transfer_info_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_info_model == channel_transfer_info_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() + assert channel_transfer_info_model_json2 == channel_transfer_info_model_json + + +class TestModel_ChannelTransferTarget: + """ + Test Class for ChannelTransferTarget + """ + + def test_channel_transfer_target_serialization(self): + """ + Test serialization/deserialization for ChannelTransferTarget + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a json representation of a ChannelTransferTarget model + channel_transfer_target_model_json = {} + channel_transfer_target_model_json['chat'] = channel_transfer_target_chat_model + + # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation + channel_transfer_target_model = ChannelTransferTarget.from_dict(channel_transfer_target_model_json) + assert channel_transfer_target_model != False + + # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation + channel_transfer_target_model_dict = ChannelTransferTarget.from_dict(channel_transfer_target_model_json).__dict__ + channel_transfer_target_model2 = ChannelTransferTarget(**channel_transfer_target_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_target_model == channel_transfer_target_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() + assert channel_transfer_target_model_json2 == channel_transfer_target_model_json + + +class TestModel_ChannelTransferTargetChat: + """ + Test Class for ChannelTransferTargetChat + """ + + def test_channel_transfer_target_chat_serialization(self): + """ + Test serialization/deserialization for ChannelTransferTargetChat + """ + + # Construct a json representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model_json = {} + channel_transfer_target_chat_model_json['url'] = 'testString' + + # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation + channel_transfer_target_chat_model = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json) + assert channel_transfer_target_chat_model != False + + # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation + channel_transfer_target_chat_model_dict = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json).__dict__ + channel_transfer_target_chat_model2 = ChannelTransferTargetChat(**channel_transfer_target_chat_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_target_chat_model == channel_transfer_target_chat_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() + assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json + + +class TestModel_CreateAssistantReleaseImportResponse: + """ + Test Class for CreateAssistantReleaseImportResponse + """ + + def test_create_assistant_release_import_response_serialization(self): + """ + Test serialization/deserialization for CreateAssistantReleaseImportResponse + """ + + # Construct a json representation of a CreateAssistantReleaseImportResponse model + create_assistant_release_import_response_model_json = {} + create_assistant_release_import_response_model_json['skill_impact_in_draft'] = ['action'] + + # Construct a model instance of CreateAssistantReleaseImportResponse by calling from_dict on the json representation + create_assistant_release_import_response_model = CreateAssistantReleaseImportResponse.from_dict(create_assistant_release_import_response_model_json) + assert create_assistant_release_import_response_model != False + + # Construct a model instance of CreateAssistantReleaseImportResponse by calling from_dict on the json representation + create_assistant_release_import_response_model_dict = CreateAssistantReleaseImportResponse.from_dict(create_assistant_release_import_response_model_json).__dict__ + create_assistant_release_import_response_model2 = CreateAssistantReleaseImportResponse(**create_assistant_release_import_response_model_dict) + + # Verify the model instances are equivalent + assert create_assistant_release_import_response_model == create_assistant_release_import_response_model2 + + # Convert model instance back to dict and verify no loss of data + create_assistant_release_import_response_model_json2 = create_assistant_release_import_response_model.to_dict() + assert create_assistant_release_import_response_model_json2 == create_assistant_release_import_response_model_json + + +class TestModel_CreateReleaseExportWithStatusErrors: + """ + Test Class for CreateReleaseExportWithStatusErrors + """ + + def test_create_release_export_with_status_errors_serialization(self): + """ + Test serialization/deserialization for CreateReleaseExportWithStatusErrors + """ + + # Construct a json representation of a CreateReleaseExportWithStatusErrors model + create_release_export_with_status_errors_model_json = {} + + # Construct a model instance of CreateReleaseExportWithStatusErrors by calling from_dict on the json representation + create_release_export_with_status_errors_model = CreateReleaseExportWithStatusErrors.from_dict(create_release_export_with_status_errors_model_json) + assert create_release_export_with_status_errors_model != False + + # Construct a model instance of CreateReleaseExportWithStatusErrors by calling from_dict on the json representation + create_release_export_with_status_errors_model_dict = CreateReleaseExportWithStatusErrors.from_dict(create_release_export_with_status_errors_model_json).__dict__ + create_release_export_with_status_errors_model2 = CreateReleaseExportWithStatusErrors(**create_release_export_with_status_errors_model_dict) + + # Verify the model instances are equivalent + assert create_release_export_with_status_errors_model == create_release_export_with_status_errors_model2 + + # Convert model instance back to dict and verify no loss of data + create_release_export_with_status_errors_model_json2 = create_release_export_with_status_errors_model.to_dict() + assert create_release_export_with_status_errors_model_json2 == create_release_export_with_status_errors_model_json + + +class TestModel_DialogLogMessage: + """ + Test Class for DialogLogMessage + """ + + def test_dialog_log_message_serialization(self): + """ + Test serialization/deserialization for DialogLogMessage + """ + + # Construct dict forms of any model objects needed in order to build this model. + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + # Construct a json representation of a DialogLogMessage model + dialog_log_message_model_json = {} + dialog_log_message_model_json['level'] = 'info' + dialog_log_message_model_json['message'] = 'testString' + dialog_log_message_model_json['code'] = 'testString' + dialog_log_message_model_json['source'] = log_message_source_model + + # Construct a model instance of DialogLogMessage by calling from_dict on the json representation + dialog_log_message_model = DialogLogMessage.from_dict(dialog_log_message_model_json) + assert dialog_log_message_model != False + + # Construct a model instance of DialogLogMessage by calling from_dict on the json representation + dialog_log_message_model_dict = DialogLogMessage.from_dict(dialog_log_message_model_json).__dict__ + dialog_log_message_model2 = DialogLogMessage(**dialog_log_message_model_dict) + + # Verify the model instances are equivalent + assert dialog_log_message_model == dialog_log_message_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_log_message_model_json2 = dialog_log_message_model.to_dict() + assert dialog_log_message_model_json2 == dialog_log_message_model_json + + +class TestModel_DialogNodeAction: + """ + Test Class for DialogNodeAction + """ + + def test_dialog_node_action_serialization(self): + """ + Test serialization/deserialization for DialogNodeAction + """ + + # Construct a json representation of a DialogNodeAction model + dialog_node_action_model_json = {} + dialog_node_action_model_json['name'] = 'testString' + dialog_node_action_model_json['type'] = 'client' + dialog_node_action_model_json['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model_json['result_variable'] = 'testString' + dialog_node_action_model_json['credentials'] = 'testString' + + # Construct a model instance of DialogNodeAction by calling from_dict on the json representation + dialog_node_action_model = DialogNodeAction.from_dict(dialog_node_action_model_json) + assert dialog_node_action_model != False + + # Construct a model instance of DialogNodeAction by calling from_dict on the json representation + dialog_node_action_model_dict = DialogNodeAction.from_dict(dialog_node_action_model_json).__dict__ + dialog_node_action_model2 = DialogNodeAction(**dialog_node_action_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_action_model == dialog_node_action_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_action_model_json2 = dialog_node_action_model.to_dict() + assert dialog_node_action_model_json2 == dialog_node_action_model_json + + +class TestModel_DialogNodeOutputConnectToAgentTransferInfo: + """ + Test Class for DialogNodeOutputConnectToAgentTransferInfo + """ + + def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): """ - Test serialization/deserialization for BaseEnvironmentOrchestration + Test serialization/deserialization for DialogNodeOutputConnectToAgentTransferInfo + """ + + # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model + dialog_node_output_connect_to_agent_transfer_info_model_json = {} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'anyKey': 'anyValue'}} + + # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation + dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) + assert dialog_node_output_connect_to_agent_transfer_info_model != False + + # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation + dialog_node_output_connect_to_agent_transfer_info_model_dict = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json).__dict__ + dialog_node_output_connect_to_agent_transfer_info_model2 = DialogNodeOutputConnectToAgentTransferInfo(**dialog_node_output_connect_to_agent_transfer_info_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_connect_to_agent_transfer_info_model == dialog_node_output_connect_to_agent_transfer_info_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() + assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json + + +class TestModel_DialogNodeOutputOptionsElement: + """ + Test Class for DialogNodeOutputOptionsElement + """ + + def test_dialog_node_output_options_element_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputOptionsElement + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + + # Construct a json representation of a DialogNodeOutputOptionsElement model + dialog_node_output_options_element_model_json = {} + dialog_node_output_options_element_model_json['label'] = 'testString' + dialog_node_output_options_element_model_json['value'] = dialog_node_output_options_element_value_model + + # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation + dialog_node_output_options_element_model = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json) + assert dialog_node_output_options_element_model != False + + # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation + dialog_node_output_options_element_model_dict = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json).__dict__ + dialog_node_output_options_element_model2 = DialogNodeOutputOptionsElement(**dialog_node_output_options_element_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_options_element_model == dialog_node_output_options_element_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() + assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json + + +class TestModel_DialogNodeOutputOptionsElementValue: + """ + Test Class for DialogNodeOutputOptionsElementValue + """ + + def test_dialog_node_output_options_element_value_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputOptionsElementValue """ - # Construct a json representation of a BaseEnvironmentOrchestration model - base_environment_orchestration_model_json = {} - base_environment_orchestration_model_json['search_skill_fallback'] = True + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model - # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation - base_environment_orchestration_model = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json) - assert base_environment_orchestration_model != False + # Construct a json representation of a DialogNodeOutputOptionsElementValue model + dialog_node_output_options_element_value_model_json = {} + dialog_node_output_options_element_value_model_json['input'] = message_input_model - # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation - base_environment_orchestration_model_dict = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json).__dict__ - base_environment_orchestration_model2 = BaseEnvironmentOrchestration(**base_environment_orchestration_model_dict) + # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation + dialog_node_output_options_element_value_model = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json) + assert dialog_node_output_options_element_value_model != False + + # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation + dialog_node_output_options_element_value_model_dict = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json).__dict__ + dialog_node_output_options_element_value_model2 = DialogNodeOutputOptionsElementValue(**dialog_node_output_options_element_value_model_dict) # Verify the model instances are equivalent - assert base_environment_orchestration_model == base_environment_orchestration_model2 + assert dialog_node_output_options_element_value_model == dialog_node_output_options_element_value_model2 # Convert model instance back to dict and verify no loss of data - base_environment_orchestration_model_json2 = base_environment_orchestration_model.to_dict() - assert base_environment_orchestration_model_json2 == base_environment_orchestration_model_json + dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() + assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json -class TestModel_BaseEnvironmentReleaseReference: +class TestModel_DialogNodeVisited: """ - Test Class for BaseEnvironmentReleaseReference + Test Class for DialogNodeVisited """ - def test_base_environment_release_reference_serialization(self): + def test_dialog_node_visited_serialization(self): """ - Test serialization/deserialization for BaseEnvironmentReleaseReference + Test serialization/deserialization for DialogNodeVisited """ - # Construct a json representation of a BaseEnvironmentReleaseReference model - base_environment_release_reference_model_json = {} - base_environment_release_reference_model_json['release'] = 'testString' + # Construct a json representation of a DialogNodeVisited model + dialog_node_visited_model_json = {} + dialog_node_visited_model_json['dialog_node'] = 'testString' + dialog_node_visited_model_json['title'] = 'testString' + dialog_node_visited_model_json['conditions'] = 'testString' - # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation - base_environment_release_reference_model = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json) - assert base_environment_release_reference_model != False + # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation + dialog_node_visited_model = DialogNodeVisited.from_dict(dialog_node_visited_model_json) + assert dialog_node_visited_model != False - # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation - base_environment_release_reference_model_dict = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json).__dict__ - base_environment_release_reference_model2 = BaseEnvironmentReleaseReference(**base_environment_release_reference_model_dict) + # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation + dialog_node_visited_model_dict = DialogNodeVisited.from_dict(dialog_node_visited_model_json).__dict__ + dialog_node_visited_model2 = DialogNodeVisited(**dialog_node_visited_model_dict) # Verify the model instances are equivalent - assert base_environment_release_reference_model == base_environment_release_reference_model2 + assert dialog_node_visited_model == dialog_node_visited_model2 # Convert model instance back to dict and verify no loss of data - base_environment_release_reference_model_json2 = base_environment_release_reference_model.to_dict() - assert base_environment_release_reference_model_json2 == base_environment_release_reference_model_json + dialog_node_visited_model_json2 = dialog_node_visited_model.to_dict() + assert dialog_node_visited_model_json2 == dialog_node_visited_model_json -class TestModel_BulkClassifyOutput: +class TestModel_DialogSuggestion: """ - Test Class for BulkClassifyOutput + Test Class for DialogSuggestion """ - def test_bulk_classify_output_serialization(self): + def test_dialog_suggestion_serialization(self): """ - Test serialization/deserialization for BulkClassifyOutput + Test serialization/deserialization for DialogSuggestion """ # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance - bulk_classify_utterance_model['text'] = 'testString' + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3650,47 +6319,79 @@ def test_bulk_classify_output_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' - # Construct a json representation of a BulkClassifyOutput model - bulk_classify_output_model_json = {} - bulk_classify_output_model_json['input'] = bulk_classify_utterance_model - bulk_classify_output_model_json['entities'] = [runtime_entity_model] - bulk_classify_output_model_json['intents'] = [runtime_intent_model] + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' - # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation - bulk_classify_output_model = BulkClassifyOutput.from_dict(bulk_classify_output_model_json) - assert bulk_classify_output_model != False + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation - bulk_classify_output_model_dict = BulkClassifyOutput.from_dict(bulk_classify_output_model_json).__dict__ - bulk_classify_output_model2 = BulkClassifyOutput(**bulk_classify_output_model_dict) + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model['input'] = message_input_model + + # Construct a json representation of a DialogSuggestion model + dialog_suggestion_model_json = {} + dialog_suggestion_model_json['label'] = 'testString' + dialog_suggestion_model_json['value'] = dialog_suggestion_value_model + dialog_suggestion_model_json['output'] = {'anyKey': 'anyValue'} + + # Construct a model instance of DialogSuggestion by calling from_dict on the json representation + dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) + assert dialog_suggestion_model != False + + # Construct a model instance of DialogSuggestion by calling from_dict on the json representation + dialog_suggestion_model_dict = DialogSuggestion.from_dict(dialog_suggestion_model_json).__dict__ + dialog_suggestion_model2 = DialogSuggestion(**dialog_suggestion_model_dict) # Verify the model instances are equivalent - assert bulk_classify_output_model == bulk_classify_output_model2 + assert dialog_suggestion_model == dialog_suggestion_model2 # Convert model instance back to dict and verify no loss of data - bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() - assert bulk_classify_output_model_json2 == bulk_classify_output_model_json + dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() + assert dialog_suggestion_model_json2 == dialog_suggestion_model_json -class TestModel_BulkClassifyResponse: +class TestModel_DialogSuggestionValue: """ - Test Class for BulkClassifyResponse + Test Class for DialogSuggestionValue """ - def test_bulk_classify_response_serialization(self): + def test_dialog_suggestion_value_serialization(self): """ - Test serialization/deserialization for BulkClassifyResponse + Test serialization/deserialization for DialogSuggestionValue """ # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance - bulk_classify_utterance_model['text'] = 'testString' + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3742,311 +6443,265 @@ def test_bulk_classify_response_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' - - bulk_classify_output_model = {} # BulkClassifyOutput - bulk_classify_output_model['input'] = bulk_classify_utterance_model - bulk_classify_output_model['entities'] = [runtime_entity_model] - bulk_classify_output_model['intents'] = [runtime_intent_model] - - # Construct a json representation of a BulkClassifyResponse model - bulk_classify_response_model_json = {} - bulk_classify_response_model_json['output'] = [bulk_classify_output_model] - - # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation - bulk_classify_response_model = BulkClassifyResponse.from_dict(bulk_classify_response_model_json) - assert bulk_classify_response_model != False - - # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation - bulk_classify_response_model_dict = BulkClassifyResponse.from_dict(bulk_classify_response_model_json).__dict__ - bulk_classify_response_model2 = BulkClassifyResponse(**bulk_classify_response_model_dict) - - # Verify the model instances are equivalent - assert bulk_classify_response_model == bulk_classify_response_model2 - - # Convert model instance back to dict and verify no loss of data - bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() - assert bulk_classify_response_model_json2 == bulk_classify_response_model_json - - -class TestModel_BulkClassifyUtterance: - """ - Test Class for BulkClassifyUtterance - """ - - def test_bulk_classify_utterance_serialization(self): - """ - Test serialization/deserialization for BulkClassifyUtterance - """ - - # Construct a json representation of a BulkClassifyUtterance model - bulk_classify_utterance_model_json = {} - bulk_classify_utterance_model_json['text'] = 'testString' - - # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation - bulk_classify_utterance_model = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json) - assert bulk_classify_utterance_model != False - - # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation - bulk_classify_utterance_model_dict = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json).__dict__ - bulk_classify_utterance_model2 = BulkClassifyUtterance(**bulk_classify_utterance_model_dict) - - # Verify the model instances are equivalent - assert bulk_classify_utterance_model == bulk_classify_utterance_model2 + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' - # Convert model instance back to dict and verify no loss of data - bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() - assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True -class TestModel_CaptureGroup: - """ - Test Class for CaptureGroup - """ + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False - def test_capture_group_serialization(self): - """ - Test serialization/deserialization for CaptureGroup - """ + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model - # Construct a json representation of a CaptureGroup model - capture_group_model_json = {} - capture_group_model_json['group'] = 'testString' - capture_group_model_json['location'] = [38] + # Construct a json representation of a DialogSuggestionValue model + dialog_suggestion_value_model_json = {} + dialog_suggestion_value_model_json['input'] = message_input_model - # Construct a model instance of CaptureGroup by calling from_dict on the json representation - capture_group_model = CaptureGroup.from_dict(capture_group_model_json) - assert capture_group_model != False + # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation + dialog_suggestion_value_model = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json) + assert dialog_suggestion_value_model != False - # Construct a model instance of CaptureGroup by calling from_dict on the json representation - capture_group_model_dict = CaptureGroup.from_dict(capture_group_model_json).__dict__ - capture_group_model2 = CaptureGroup(**capture_group_model_dict) + # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation + dialog_suggestion_value_model_dict = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json).__dict__ + dialog_suggestion_value_model2 = DialogSuggestionValue(**dialog_suggestion_value_model_dict) # Verify the model instances are equivalent - assert capture_group_model == capture_group_model2 + assert dialog_suggestion_value_model == dialog_suggestion_value_model2 # Convert model instance back to dict and verify no loss of data - capture_group_model_json2 = capture_group_model.to_dict() - assert capture_group_model_json2 == capture_group_model_json + dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() + assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json -class TestModel_ChannelTransferInfo: +class TestModel_Environment: """ - Test Class for ChannelTransferInfo + Test Class for Environment """ - def test_channel_transfer_info_serialization(self): + def test_environment_serialization(self): """ - Test serialization/deserialization for ChannelTransferInfo + Test serialization/deserialization for Environment """ # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat - channel_transfer_target_chat_model['url'] = 'testString' + base_environment_orchestration_model = {} # BaseEnvironmentOrchestration + base_environment_orchestration_model['search_skill_fallback'] = True - channel_transfer_target_model = {} # ChannelTransferTarget - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + environment_skill_model = {} # EnvironmentSkill + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' - # Construct a json representation of a ChannelTransferInfo model - channel_transfer_info_model_json = {} - channel_transfer_info_model_json['target'] = channel_transfer_target_model + # Construct a json representation of a Environment model + environment_model_json = {} + environment_model_json['name'] = 'testString' + environment_model_json['description'] = 'testString' + environment_model_json['orchestration'] = base_environment_orchestration_model + environment_model_json['session_timeout'] = 10 + environment_model_json['skill_references'] = [environment_skill_model] - # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation - channel_transfer_info_model = ChannelTransferInfo.from_dict(channel_transfer_info_model_json) - assert channel_transfer_info_model != False + # Construct a model instance of Environment by calling from_dict on the json representation + environment_model = Environment.from_dict(environment_model_json) + assert environment_model != False - # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation - channel_transfer_info_model_dict = ChannelTransferInfo.from_dict(channel_transfer_info_model_json).__dict__ - channel_transfer_info_model2 = ChannelTransferInfo(**channel_transfer_info_model_dict) + # Construct a model instance of Environment by calling from_dict on the json representation + environment_model_dict = Environment.from_dict(environment_model_json).__dict__ + environment_model2 = Environment(**environment_model_dict) # Verify the model instances are equivalent - assert channel_transfer_info_model == channel_transfer_info_model2 + assert environment_model == environment_model2 # Convert model instance back to dict and verify no loss of data - channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() - assert channel_transfer_info_model_json2 == channel_transfer_info_model_json + environment_model_json2 = environment_model.to_dict() + assert environment_model_json2 == environment_model_json -class TestModel_ChannelTransferTarget: +class TestModel_EnvironmentCollection: """ - Test Class for ChannelTransferTarget + Test Class for EnvironmentCollection """ - def test_channel_transfer_target_serialization(self): + def test_environment_collection_serialization(self): """ - Test serialization/deserialization for ChannelTransferTarget + Test serialization/deserialization for EnvironmentCollection """ # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat - channel_transfer_target_chat_model['url'] = 'testString' - - # Construct a json representation of a ChannelTransferTarget model - channel_transfer_target_model_json = {} - channel_transfer_target_model_json['chat'] = channel_transfer_target_chat_model - - # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation - channel_transfer_target_model = ChannelTransferTarget.from_dict(channel_transfer_target_model_json) - assert channel_transfer_target_model != False - - # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation - channel_transfer_target_model_dict = ChannelTransferTarget.from_dict(channel_transfer_target_model_json).__dict__ - channel_transfer_target_model2 = ChannelTransferTarget(**channel_transfer_target_model_dict) - - # Verify the model instances are equivalent - assert channel_transfer_target_model == channel_transfer_target_model2 - - # Convert model instance back to dict and verify no loss of data - channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() - assert channel_transfer_target_model_json2 == channel_transfer_target_model_json + base_environment_orchestration_model = {} # BaseEnvironmentOrchestration + base_environment_orchestration_model['search_skill_fallback'] = True + environment_skill_model = {} # EnvironmentSkill + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' -class TestModel_ChannelTransferTargetChat: - """ - Test Class for ChannelTransferTargetChat - """ + environment_model = {} # Environment + environment_model['name'] = 'testString' + environment_model['description'] = 'testString' + environment_model['orchestration'] = base_environment_orchestration_model + environment_model['session_timeout'] = 10 + environment_model['skill_references'] = [environment_skill_model] - def test_channel_transfer_target_chat_serialization(self): - """ - Test serialization/deserialization for ChannelTransferTargetChat - """ + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' - # Construct a json representation of a ChannelTransferTargetChat model - channel_transfer_target_chat_model_json = {} - channel_transfer_target_chat_model_json['url'] = 'testString' + # Construct a json representation of a EnvironmentCollection model + environment_collection_model_json = {} + environment_collection_model_json['environments'] = [environment_model] + environment_collection_model_json['pagination'] = pagination_model - # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation - channel_transfer_target_chat_model = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json) - assert channel_transfer_target_chat_model != False + # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation + environment_collection_model = EnvironmentCollection.from_dict(environment_collection_model_json) + assert environment_collection_model != False - # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation - channel_transfer_target_chat_model_dict = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json).__dict__ - channel_transfer_target_chat_model2 = ChannelTransferTargetChat(**channel_transfer_target_chat_model_dict) + # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation + environment_collection_model_dict = EnvironmentCollection.from_dict(environment_collection_model_json).__dict__ + environment_collection_model2 = EnvironmentCollection(**environment_collection_model_dict) # Verify the model instances are equivalent - assert channel_transfer_target_chat_model == channel_transfer_target_chat_model2 + assert environment_collection_model == environment_collection_model2 # Convert model instance back to dict and verify no loss of data - channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() - assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json + environment_collection_model_json2 = environment_collection_model.to_dict() + assert environment_collection_model_json2 == environment_collection_model_json -class TestModel_DialogLogMessage: +class TestModel_EnvironmentReference: """ - Test Class for DialogLogMessage + Test Class for EnvironmentReference """ - def test_dialog_log_message_serialization(self): + def test_environment_reference_serialization(self): """ - Test serialization/deserialization for DialogLogMessage + Test serialization/deserialization for EnvironmentReference """ - # Construct dict forms of any model objects needed in order to build this model. - - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' - - # Construct a json representation of a DialogLogMessage model - dialog_log_message_model_json = {} - dialog_log_message_model_json['level'] = 'info' - dialog_log_message_model_json['message'] = 'testString' - dialog_log_message_model_json['code'] = 'testString' - dialog_log_message_model_json['source'] = log_message_source_model + # Construct a json representation of a EnvironmentReference model + environment_reference_model_json = {} + environment_reference_model_json['name'] = 'testString' - # Construct a model instance of DialogLogMessage by calling from_dict on the json representation - dialog_log_message_model = DialogLogMessage.from_dict(dialog_log_message_model_json) - assert dialog_log_message_model != False + # Construct a model instance of EnvironmentReference by calling from_dict on the json representation + environment_reference_model = EnvironmentReference.from_dict(environment_reference_model_json) + assert environment_reference_model != False - # Construct a model instance of DialogLogMessage by calling from_dict on the json representation - dialog_log_message_model_dict = DialogLogMessage.from_dict(dialog_log_message_model_json).__dict__ - dialog_log_message_model2 = DialogLogMessage(**dialog_log_message_model_dict) + # Construct a model instance of EnvironmentReference by calling from_dict on the json representation + environment_reference_model_dict = EnvironmentReference.from_dict(environment_reference_model_json).__dict__ + environment_reference_model2 = EnvironmentReference(**environment_reference_model_dict) # Verify the model instances are equivalent - assert dialog_log_message_model == dialog_log_message_model2 + assert environment_reference_model == environment_reference_model2 # Convert model instance back to dict and verify no loss of data - dialog_log_message_model_json2 = dialog_log_message_model.to_dict() - assert dialog_log_message_model_json2 == dialog_log_message_model_json + environment_reference_model_json2 = environment_reference_model.to_dict() + assert environment_reference_model_json2 == environment_reference_model_json -class TestModel_DialogNodeAction: +class TestModel_EnvironmentSkill: """ - Test Class for DialogNodeAction + Test Class for EnvironmentSkill """ - def test_dialog_node_action_serialization(self): + def test_environment_skill_serialization(self): """ - Test serialization/deserialization for DialogNodeAction + Test serialization/deserialization for EnvironmentSkill """ - # Construct a json representation of a DialogNodeAction model - dialog_node_action_model_json = {} - dialog_node_action_model_json['name'] = 'testString' - dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model_json['result_variable'] = 'testString' - dialog_node_action_model_json['credentials'] = 'testString' + # Construct a json representation of a EnvironmentSkill model + environment_skill_model_json = {} + environment_skill_model_json['skill_id'] = 'testString' + environment_skill_model_json['type'] = 'dialog' + environment_skill_model_json['disabled'] = True + environment_skill_model_json['snapshot'] = 'testString' + environment_skill_model_json['skill_reference'] = 'testString' - # Construct a model instance of DialogNodeAction by calling from_dict on the json representation - dialog_node_action_model = DialogNodeAction.from_dict(dialog_node_action_model_json) - assert dialog_node_action_model != False + # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation + environment_skill_model = EnvironmentSkill.from_dict(environment_skill_model_json) + assert environment_skill_model != False - # Construct a model instance of DialogNodeAction by calling from_dict on the json representation - dialog_node_action_model_dict = DialogNodeAction.from_dict(dialog_node_action_model_json).__dict__ - dialog_node_action_model2 = DialogNodeAction(**dialog_node_action_model_dict) + # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation + environment_skill_model_dict = EnvironmentSkill.from_dict(environment_skill_model_json).__dict__ + environment_skill_model2 = EnvironmentSkill(**environment_skill_model_dict) # Verify the model instances are equivalent - assert dialog_node_action_model == dialog_node_action_model2 + assert environment_skill_model == environment_skill_model2 # Convert model instance back to dict and verify no loss of data - dialog_node_action_model_json2 = dialog_node_action_model.to_dict() - assert dialog_node_action_model_json2 == dialog_node_action_model_json + environment_skill_model_json2 = environment_skill_model.to_dict() + assert environment_skill_model_json2 == environment_skill_model_json -class TestModel_DialogNodeOutputConnectToAgentTransferInfo: +class TestModel_IntegrationReference: """ - Test Class for DialogNodeOutputConnectToAgentTransferInfo + Test Class for IntegrationReference """ - def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): + def test_integration_reference_serialization(self): """ - Test serialization/deserialization for DialogNodeOutputConnectToAgentTransferInfo + Test serialization/deserialization for IntegrationReference """ - # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model - dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'anyKey': 'anyValue'}} + # Construct a json representation of a IntegrationReference model + integration_reference_model_json = {} + integration_reference_model_json['integration_id'] = 'testString' + integration_reference_model_json['type'] = 'testString' - # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation - dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) - assert dialog_node_output_connect_to_agent_transfer_info_model != False + # Construct a model instance of IntegrationReference by calling from_dict on the json representation + integration_reference_model = IntegrationReference.from_dict(integration_reference_model_json) + assert integration_reference_model != False - # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation - dialog_node_output_connect_to_agent_transfer_info_model_dict = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json).__dict__ - dialog_node_output_connect_to_agent_transfer_info_model2 = DialogNodeOutputConnectToAgentTransferInfo(**dialog_node_output_connect_to_agent_transfer_info_model_dict) + # Construct a model instance of IntegrationReference by calling from_dict on the json representation + integration_reference_model_dict = IntegrationReference.from_dict(integration_reference_model_json).__dict__ + integration_reference_model2 = IntegrationReference(**integration_reference_model_dict) # Verify the model instances are equivalent - assert dialog_node_output_connect_to_agent_transfer_info_model == dialog_node_output_connect_to_agent_transfer_info_model2 + assert integration_reference_model == integration_reference_model2 # Convert model instance back to dict and verify no loss of data - dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() - assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json + integration_reference_model_json2 = integration_reference_model.to_dict() + assert integration_reference_model_json2 == integration_reference_model_json -class TestModel_DialogNodeOutputOptionsElement: +class TestModel_Log: """ - Test Class for DialogNodeOutputOptionsElement + Test Class for Log """ - def test_dialog_node_output_options_element_serialization(self): + def test_log_serialization(self): """ - Test serialization/deserialization for DialogNodeOutputOptionsElement + Test serialization/deserialization for Log """ # Construct dict forms of any model objects needed in order to build this model. @@ -4128,199 +6783,165 @@ def test_dialog_node_output_options_element_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model - - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - - # Construct a json representation of a DialogNodeOutputOptionsElement model - dialog_node_output_options_element_model_json = {} - dialog_node_output_options_element_model_json['label'] = 'testString' - dialog_node_output_options_element_model_json['value'] = dialog_node_output_options_element_value_model - - # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation - dialog_node_output_options_element_model = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json) - assert dialog_node_output_options_element_model != False - - # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation - dialog_node_output_options_element_model_dict = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json).__dict__ - dialog_node_output_options_element_model2 = DialogNodeOutputOptionsElement(**dialog_node_output_options_element_model_dict) - - # Verify the model instances are equivalent - assert dialog_node_output_options_element_model == dialog_node_output_options_element_model2 - - # Convert model instance back to dict and verify no loss of data - dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() - assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json - - -class TestModel_DialogNodeOutputOptionsElementValue: - """ - Test Class for DialogNodeOutputOptionsElementValue - """ - - def test_dialog_node_output_options_element_value_serialization(self): - """ - Test serialization/deserialization for DialogNodeOutputOptionsElementValue - """ + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'testString' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model - # Construct dict forms of any model objects needed in order to build this model. + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + log_request_model = {} # LogRequest + log_request_model['input'] = log_request_input_model + log_request_model['context'] = message_context_model + log_request_model['user_id'] = 'testString' - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['async_callout'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - # Construct a json representation of a DialogNodeOutputOptionsElementValue model - dialog_node_output_options_element_value_model_json = {} - dialog_node_output_options_element_value_model_json['input'] = message_input_model + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' - # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation - dialog_node_output_options_element_value_model = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json) - assert dialog_node_output_options_element_value_model != False + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model - # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation - dialog_node_output_options_element_value_model_dict = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json).__dict__ - dialog_node_output_options_element_value_model2 = DialogNodeOutputOptionsElementValue(**dialog_node_output_options_element_value_model_dict) + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - # Verify the model instances are equivalent - assert dialog_node_output_options_element_value_model == dialog_node_output_options_element_value_model2 + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' - # Convert model instance back to dict and verify no loss of data - dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() - assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' -class TestModel_DialogNodeVisited: - """ - Test Class for DialogNodeVisited - """ + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model - def test_dialog_node_visited_serialization(self): - """ - Test serialization/deserialization for DialogNodeVisited - """ + log_response_model = {} # LogResponse + log_response_model['output'] = log_response_output_model + log_response_model['context'] = message_context_model + log_response_model['user_id'] = 'testString' - # Construct a json representation of a DialogNodeVisited model - dialog_node_visited_model_json = {} - dialog_node_visited_model_json['dialog_node'] = 'testString' - dialog_node_visited_model_json['title'] = 'testString' - dialog_node_visited_model_json['conditions'] = 'testString' + # Construct a json representation of a Log model + log_model_json = {} + log_model_json['log_id'] = 'testString' + log_model_json['request'] = log_request_model + log_model_json['response'] = log_response_model + log_model_json['assistant_id'] = 'testString' + log_model_json['session_id'] = 'testString' + log_model_json['skill_id'] = 'testString' + log_model_json['snapshot'] = 'testString' + log_model_json['request_timestamp'] = 'testString' + log_model_json['response_timestamp'] = 'testString' + log_model_json['language'] = 'testString' + log_model_json['customer_id'] = 'testString' - # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation - dialog_node_visited_model = DialogNodeVisited.from_dict(dialog_node_visited_model_json) - assert dialog_node_visited_model != False + # Construct a model instance of Log by calling from_dict on the json representation + log_model = Log.from_dict(log_model_json) + assert log_model != False - # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation - dialog_node_visited_model_dict = DialogNodeVisited.from_dict(dialog_node_visited_model_json).__dict__ - dialog_node_visited_model2 = DialogNodeVisited(**dialog_node_visited_model_dict) + # Construct a model instance of Log by calling from_dict on the json representation + log_model_dict = Log.from_dict(log_model_json).__dict__ + log_model2 = Log(**log_model_dict) # Verify the model instances are equivalent - assert dialog_node_visited_model == dialog_node_visited_model2 + assert log_model == log_model2 # Convert model instance back to dict and verify no loss of data - dialog_node_visited_model_json2 = dialog_node_visited_model.to_dict() - assert dialog_node_visited_model_json2 == dialog_node_visited_model_json + log_model_json2 = log_model.to_dict() + assert log_model_json2 == log_model_json -class TestModel_DialogSuggestion: +class TestModel_LogCollection: """ - Test Class for DialogSuggestion + Test Class for LogCollection """ - def test_dialog_suggestion_serialization(self): + def test_log_collection_serialization(self): """ - Test serialization/deserialization for DialogSuggestion + Test serialization/deserialization for LogCollection """ # Construct dict forms of any model objects needed in order to build this model. @@ -4402,49 +7023,206 @@ def test_dialog_suggestion_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'testString' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model - dialog_suggestion_value_model = {} # DialogSuggestionValue - dialog_suggestion_value_model['input'] = message_input_model + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a json representation of a DialogSuggestion model - dialog_suggestion_model_json = {} - dialog_suggestion_model_json['label'] = 'testString' - dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {'anyKey': 'anyValue'} + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model - # Construct a model instance of DialogSuggestion by calling from_dict on the json representation - dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) - assert dialog_suggestion_model != False + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - # Construct a model instance of DialogSuggestion by calling from_dict on the json representation - dialog_suggestion_model_dict = DialogSuggestion.from_dict(dialog_suggestion_model_json).__dict__ - dialog_suggestion_model2 = DialogSuggestion(**dialog_suggestion_model_dict) + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + log_request_model = {} # LogRequest + log_request_model['input'] = log_request_input_model + log_request_model['context'] = message_context_model + log_request_model['user_id'] = 'testString' + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model + + log_response_model = {} # LogResponse + log_response_model['output'] = log_response_output_model + log_response_model['context'] = message_context_model + log_response_model['user_id'] = 'testString' + + log_model = {} # Log + log_model['log_id'] = 'testString' + log_model['request'] = log_request_model + log_model['response'] = log_response_model + log_model['assistant_id'] = 'testString' + log_model['session_id'] = 'testString' + log_model['skill_id'] = 'testString' + log_model['snapshot'] = 'testString' + log_model['request_timestamp'] = 'testString' + log_model['response_timestamp'] = 'testString' + log_model['language'] = 'testString' + log_model['customer_id'] = 'testString' + + log_pagination_model = {} # LogPagination + log_pagination_model['next_url'] = 'testString' + log_pagination_model['matched'] = 38 + log_pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a LogCollection model + log_collection_model_json = {} + log_collection_model_json['logs'] = [log_model] + log_collection_model_json['pagination'] = log_pagination_model + + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model = LogCollection.from_dict(log_collection_model_json) + assert log_collection_model != False + + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model_dict = LogCollection.from_dict(log_collection_model_json).__dict__ + log_collection_model2 = LogCollection(**log_collection_model_dict) # Verify the model instances are equivalent - assert dialog_suggestion_model == dialog_suggestion_model2 + assert log_collection_model == log_collection_model2 # Convert model instance back to dict and verify no loss of data - dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() - assert dialog_suggestion_model_json2 == dialog_suggestion_model_json + log_collection_model_json2 = log_collection_model.to_dict() + assert log_collection_model_json2 == log_collection_model_json + + +class TestModel_LogPagination: + """ + Test Class for LogPagination + """ + + def test_log_pagination_serialization(self): + """ + Test serialization/deserialization for LogPagination + """ + + # Construct a json representation of a LogPagination model + log_pagination_model_json = {} + log_pagination_model_json['next_url'] = 'testString' + log_pagination_model_json['matched'] = 38 + log_pagination_model_json['next_cursor'] = 'testString' + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model = LogPagination.from_dict(log_pagination_model_json) + assert log_pagination_model != False + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model_dict = LogPagination.from_dict(log_pagination_model_json).__dict__ + log_pagination_model2 = LogPagination(**log_pagination_model_dict) + + # Verify the model instances are equivalent + assert log_pagination_model == log_pagination_model2 + + # Convert model instance back to dict and verify no loss of data + log_pagination_model_json2 = log_pagination_model.to_dict() + assert log_pagination_model_json2 == log_pagination_model_json -class TestModel_DialogSuggestionValue: +class TestModel_LogRequest: """ - Test Class for DialogSuggestionValue + Test Class for LogRequest """ - def test_dialog_suggestion_value_serialization(self): + def test_log_request_serialization(self): """ - Test serialization/deserialization for DialogSuggestionValue + Test serialization/deserialization for LogRequest """ # Construct dict forms of any model objects needed in order to build this model. @@ -4523,246 +7301,85 @@ def test_dialog_suggestion_value_serialization(self): message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False - - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model - - # Construct a json representation of a DialogSuggestionValue model - dialog_suggestion_value_model_json = {} - dialog_suggestion_value_model_json['input'] = message_input_model - - # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation - dialog_suggestion_value_model = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json) - assert dialog_suggestion_value_model != False - - # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation - dialog_suggestion_value_model_dict = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json).__dict__ - dialog_suggestion_value_model2 = DialogSuggestionValue(**dialog_suggestion_value_model_dict) - - # Verify the model instances are equivalent - assert dialog_suggestion_value_model == dialog_suggestion_value_model2 - - # Convert model instance back to dict and verify no loss of data - dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() - assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json - - -class TestModel_Environment: - """ - Test Class for Environment - """ - - def test_environment_serialization(self): - """ - Test serialization/deserialization for Environment - """ - - # Construct dict forms of any model objects needed in order to build this model. - - base_environment_orchestration_model = {} # BaseEnvironmentOrchestration - base_environment_orchestration_model['search_skill_fallback'] = True - - environment_skill_model = {} # EnvironmentSkill - environment_skill_model['skill_id'] = 'testString' - environment_skill_model['type'] = 'dialog' - environment_skill_model['disabled'] = True - environment_skill_model['snapshot'] = 'testString' - environment_skill_model['skill_reference'] = 'testString' - - # Construct a json representation of a Environment model - environment_model_json = {} - environment_model_json['name'] = 'testString' - environment_model_json['description'] = 'testString' - environment_model_json['orchestration'] = base_environment_orchestration_model - environment_model_json['session_timeout'] = 10 - environment_model_json['skill_references'] = [environment_skill_model] - - # Construct a model instance of Environment by calling from_dict on the json representation - environment_model = Environment.from_dict(environment_model_json) - assert environment_model != False - - # Construct a model instance of Environment by calling from_dict on the json representation - environment_model_dict = Environment.from_dict(environment_model_json).__dict__ - environment_model2 = Environment(**environment_model_dict) - - # Verify the model instances are equivalent - assert environment_model == environment_model2 - - # Convert model instance back to dict and verify no loss of data - environment_model_json2 = environment_model.to_dict() - assert environment_model_json2 == environment_model_json - - -class TestModel_EnvironmentCollection: - """ - Test Class for EnvironmentCollection - """ - - def test_environment_collection_serialization(self): - """ - Test serialization/deserialization for EnvironmentCollection - """ - - # Construct dict forms of any model objects needed in order to build this model. - - base_environment_orchestration_model = {} # BaseEnvironmentOrchestration - base_environment_orchestration_model['search_skill_fallback'] = True - - environment_skill_model = {} # EnvironmentSkill - environment_skill_model['skill_id'] = 'testString' - environment_skill_model['type'] = 'dialog' - environment_skill_model['disabled'] = True - environment_skill_model['snapshot'] = 'testString' - environment_skill_model['skill_reference'] = 'testString' - - environment_model = {} # Environment - environment_model['name'] = 'testString' - environment_model['description'] = 'testString' - environment_model['orchestration'] = base_environment_orchestration_model - environment_model['session_timeout'] = 10 - environment_model['skill_references'] = [environment_skill_model] - - pagination_model = {} # Pagination - pagination_model['refresh_url'] = 'testString' - pagination_model['next_url'] = 'testString' - pagination_model['total'] = 38 - pagination_model['matched'] = 38 - pagination_model['refresh_cursor'] = 'testString' - pagination_model['next_cursor'] = 'testString' - - # Construct a json representation of a EnvironmentCollection model - environment_collection_model_json = {} - environment_collection_model_json['environments'] = [environment_model] - environment_collection_model_json['pagination'] = pagination_model - - # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation - environment_collection_model = EnvironmentCollection.from_dict(environment_collection_model_json) - assert environment_collection_model != False - - # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation - environment_collection_model_dict = EnvironmentCollection.from_dict(environment_collection_model_json).__dict__ - environment_collection_model2 = EnvironmentCollection(**environment_collection_model_dict) - - # Verify the model instances are equivalent - assert environment_collection_model == environment_collection_model2 - - # Convert model instance back to dict and verify no loss of data - environment_collection_model_json2 = environment_collection_model.to_dict() - assert environment_collection_model_json2 == environment_collection_model_json - - -class TestModel_EnvironmentReference: - """ - Test Class for EnvironmentReference - """ - - def test_environment_reference_serialization(self): - """ - Test serialization/deserialization for EnvironmentReference - """ - - # Construct a json representation of a EnvironmentReference model - environment_reference_model_json = {} - environment_reference_model_json['name'] = 'testString' - - # Construct a model instance of EnvironmentReference by calling from_dict on the json representation - environment_reference_model = EnvironmentReference.from_dict(environment_reference_model_json) - assert environment_reference_model != False - - # Construct a model instance of EnvironmentReference by calling from_dict on the json representation - environment_reference_model_dict = EnvironmentReference.from_dict(environment_reference_model_json).__dict__ - environment_reference_model2 = EnvironmentReference(**environment_reference_model_dict) - - # Verify the model instances are equivalent - assert environment_reference_model == environment_reference_model2 - - # Convert model instance back to dict and verify no loss of data - environment_reference_model_json2 = environment_reference_model.to_dict() - assert environment_reference_model_json2 == environment_reference_model_json - - -class TestModel_EnvironmentSkill: - """ - Test Class for EnvironmentSkill - """ - - def test_environment_skill_serialization(self): - """ - Test serialization/deserialization for EnvironmentSkill - """ - - # Construct a json representation of a EnvironmentSkill model - environment_skill_model_json = {} - environment_skill_model_json['skill_id'] = 'testString' - environment_skill_model_json['type'] = 'dialog' - environment_skill_model_json['disabled'] = True - environment_skill_model_json['snapshot'] = 'testString' - environment_skill_model_json['skill_reference'] = 'testString' + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True - # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation - environment_skill_model = EnvironmentSkill.from_dict(environment_skill_model_json) - assert environment_skill_model != False + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'Hello' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model - # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation - environment_skill_model_dict = EnvironmentSkill.from_dict(environment_skill_model_json).__dict__ - environment_skill_model2 = EnvironmentSkill(**environment_skill_model_dict) + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'my_user_id' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Verify the model instances are equivalent - assert environment_skill_model == environment_skill_model2 + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model - # Convert model instance back to dict and verify no loss of data - environment_skill_model_json2 = environment_skill_model.to_dict() - assert environment_skill_model_json2 == environment_skill_model_json + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model -class TestModel_IntegrationReference: - """ - Test Class for IntegrationReference - """ + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - def test_integration_reference_serialization(self): - """ - Test serialization/deserialization for IntegrationReference - """ + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - # Construct a json representation of a IntegrationReference model - integration_reference_model_json = {} - integration_reference_model_json['integration_id'] = 'testString' - integration_reference_model_json['type'] = 'testString' + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} - # Construct a model instance of IntegrationReference by calling from_dict on the json representation - integration_reference_model = IntegrationReference.from_dict(integration_reference_model_json) - assert integration_reference_model != False + # Construct a json representation of a LogRequest model + log_request_model_json = {} + log_request_model_json['input'] = log_request_input_model + log_request_model_json['context'] = message_context_model + log_request_model_json['user_id'] = 'testString' - # Construct a model instance of IntegrationReference by calling from_dict on the json representation - integration_reference_model_dict = IntegrationReference.from_dict(integration_reference_model_json).__dict__ - integration_reference_model2 = IntegrationReference(**integration_reference_model_dict) + # Construct a model instance of LogRequest by calling from_dict on the json representation + log_request_model = LogRequest.from_dict(log_request_model_json) + assert log_request_model != False + + # Construct a model instance of LogRequest by calling from_dict on the json representation + log_request_model_dict = LogRequest.from_dict(log_request_model_json).__dict__ + log_request_model2 = LogRequest(**log_request_model_dict) # Verify the model instances are equivalent - assert integration_reference_model == integration_reference_model2 + assert log_request_model == log_request_model2 # Convert model instance back to dict and verify no loss of data - integration_reference_model_json2 = integration_reference_model.to_dict() - assert integration_reference_model_json2 == integration_reference_model_json + log_request_model_json2 = log_request_model.to_dict() + assert log_request_model_json2 == log_request_model_json -class TestModel_Log: +class TestModel_LogRequestInput: """ - Test Class for Log + Test Class for LogRequestInput """ - def test_log_serialization(self): + def test_log_request_input_serialization(self): """ - Test serialization/deserialization for Log + Test serialization/deserialization for LogRequestInput """ # Construct dict forms of any model objects needed in order to build this model. @@ -4844,15 +7461,164 @@ def test_log_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - log_request_input_model = {} # LogRequestInput - log_request_input_model['message_type'] = 'text' - log_request_input_model['text'] = 'testString' - log_request_input_model['intents'] = [runtime_intent_model] - log_request_input_model['entities'] = [runtime_entity_model] - log_request_input_model['suggestion_id'] = 'testString' - log_request_input_model['attachments'] = [message_input_attachment_model] - log_request_input_model['analytics'] = request_analytics_model - log_request_input_model['options'] = message_input_options_model + # Construct a json representation of a LogRequestInput model + log_request_input_model_json = {} + log_request_input_model_json['message_type'] = 'text' + log_request_input_model_json['text'] = 'testString' + log_request_input_model_json['intents'] = [runtime_intent_model] + log_request_input_model_json['entities'] = [runtime_entity_model] + log_request_input_model_json['suggestion_id'] = 'testString' + log_request_input_model_json['attachments'] = [message_input_attachment_model] + log_request_input_model_json['analytics'] = request_analytics_model + log_request_input_model_json['options'] = message_input_options_model + + # Construct a model instance of LogRequestInput by calling from_dict on the json representation + log_request_input_model = LogRequestInput.from_dict(log_request_input_model_json) + assert log_request_input_model != False + + # Construct a model instance of LogRequestInput by calling from_dict on the json representation + log_request_input_model_dict = LogRequestInput.from_dict(log_request_input_model_json).__dict__ + log_request_input_model2 = LogRequestInput(**log_request_input_model_dict) + + # Verify the model instances are equivalent + assert log_request_input_model == log_request_input_model2 + + # Convert model instance back to dict and verify no loss of data + log_request_input_model_json2 = log_request_input_model.to_dict() + assert log_request_input_model_json2 == log_request_input_model_json + + +class TestModel_LogResponse: + """ + Test Class for LogResponse + """ + + def test_log_response_serialization(self): + """ + Test serialization/deserialization for LogResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' @@ -4890,18 +7656,102 @@ def test_log_serialization(self): message_context_model['skills'] = message_context_skills_model message_context_model['integrations'] = {'anyKey': 'anyValue'} - log_request_model = {} # LogRequest - log_request_model['input'] = log_request_input_model - log_request_model['context'] = message_context_model - log_request_model['user_id'] = 'testString' + # Construct a json representation of a LogResponse model + log_response_model_json = {} + log_response_model_json['output'] = log_response_output_model + log_response_model_json['context'] = message_context_model + log_response_model_json['user_id'] = 'testString' + + # Construct a model instance of LogResponse by calling from_dict on the json representation + log_response_model = LogResponse.from_dict(log_response_model_json) + assert log_response_model != False + + # Construct a model instance of LogResponse by calling from_dict on the json representation + log_response_model_dict = LogResponse.from_dict(log_response_model_json).__dict__ + log_response_model2 = LogResponse(**log_response_model_dict) + + # Verify the model instances are equivalent + assert log_response_model == log_response_model2 + + # Convert model instance back to dict and verify no loss of data + log_response_model_json2 = log_response_model.to_dict() + assert log_response_model_json2 == log_response_model_json + + +class TestModel_LogResponseOutput: + """ + Test Class for LogResponseOutput + """ + + def test_log_response_output_serialization(self): + """ + Test serialization/deserialization for LogResponseOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -4951,148 +7801,184 @@ def test_log_serialization(self): message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - log_response_output_model = {} # LogResponseOutput - log_response_output_model['generic'] = [runtime_response_generic_model] - log_response_output_model['intents'] = [runtime_intent_model] - log_response_output_model['entities'] = [runtime_entity_model] - log_response_output_model['actions'] = [dialog_node_action_model] - log_response_output_model['debug'] = message_output_debug_model - log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} - log_response_output_model['spelling'] = message_output_spelling_model + # Construct a json representation of a LogResponseOutput model + log_response_output_model_json = {} + log_response_output_model_json['generic'] = [runtime_response_generic_model] + log_response_output_model_json['intents'] = [runtime_intent_model] + log_response_output_model_json['entities'] = [runtime_entity_model] + log_response_output_model_json['actions'] = [dialog_node_action_model] + log_response_output_model_json['debug'] = message_output_debug_model + log_response_output_model_json['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model_json['spelling'] = message_output_spelling_model - log_response_model = {} # LogResponse - log_response_model['output'] = log_response_output_model - log_response_model['context'] = message_context_model - log_response_model['user_id'] = 'testString' + # Construct a model instance of LogResponseOutput by calling from_dict on the json representation + log_response_output_model = LogResponseOutput.from_dict(log_response_output_model_json) + assert log_response_output_model != False - # Construct a json representation of a Log model - log_model_json = {} - log_model_json['log_id'] = 'testString' - log_model_json['request'] = log_request_model - log_model_json['response'] = log_response_model - log_model_json['assistant_id'] = 'testString' - log_model_json['session_id'] = 'testString' - log_model_json['skill_id'] = 'testString' - log_model_json['snapshot'] = 'testString' - log_model_json['request_timestamp'] = 'testString' - log_model_json['response_timestamp'] = 'testString' - log_model_json['language'] = 'testString' - log_model_json['customer_id'] = 'testString' + # Construct a model instance of LogResponseOutput by calling from_dict on the json representation + log_response_output_model_dict = LogResponseOutput.from_dict(log_response_output_model_json).__dict__ + log_response_output_model2 = LogResponseOutput(**log_response_output_model_dict) - # Construct a model instance of Log by calling from_dict on the json representation - log_model = Log.from_dict(log_model_json) - assert log_model != False + # Verify the model instances are equivalent + assert log_response_output_model == log_response_output_model2 - # Construct a model instance of Log by calling from_dict on the json representation - log_model_dict = Log.from_dict(log_model_json).__dict__ - log_model2 = Log(**log_model_dict) + # Convert model instance back to dict and verify no loss of data + log_response_output_model_json2 = log_response_output_model.to_dict() + assert log_response_output_model_json2 == log_response_output_model_json + + +class TestModel_MessageContext: + """ + Test Class for MessageContext + """ + + def test_message_context_serialization(self): + """ + Test serialization/deserialization for MessageContext + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + # Construct a json representation of a MessageContext model + message_context_model_json = {} + message_context_model_json['global'] = message_context_global_model + message_context_model_json['skills'] = message_context_skills_model + message_context_model_json['integrations'] = {'anyKey': 'anyValue'} + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model = MessageContext.from_dict(message_context_model_json) + assert message_context_model != False + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ + message_context_model2 = MessageContext(**message_context_model_dict) # Verify the model instances are equivalent - assert log_model == log_model2 + assert message_context_model == message_context_model2 # Convert model instance back to dict and verify no loss of data - log_model_json2 = log_model.to_dict() - assert log_model_json2 == log_model_json + message_context_model_json2 = message_context_model.to_dict() + assert message_context_model_json2 == message_context_model_json -class TestModel_LogCollection: +class TestModel_MessageContextActionSkill: """ - Test Class for LogCollection + Test Class for MessageContextActionSkill """ - def test_log_collection_serialization(self): + def test_message_context_action_skill_serialization(self): """ - Test serialization/deserialization for LogCollection + Test serialization/deserialization for MessageContextActionSkill """ # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Construct a json representation of a MessageContextActionSkill model + message_context_action_skill_model_json = {} + message_context_action_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model_json['system'] = message_context_skill_system_model + message_context_action_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation + message_context_action_skill_model = MessageContextActionSkill.from_dict(message_context_action_skill_model_json) + assert message_context_action_skill_model != False - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation + message_context_action_skill_model_dict = MessageContextActionSkill.from_dict(message_context_action_skill_model_json).__dict__ + message_context_action_skill_model2 = MessageContextActionSkill(**message_context_action_skill_model_dict) + + # Verify the model instances are equivalent + assert message_context_action_skill_model == message_context_action_skill_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_action_skill_model_json2 = message_context_action_skill_model.to_dict() + assert message_context_action_skill_model_json2 == message_context_action_skill_model_json + + +class TestModel_MessageContextDialogSkill: + """ + Test Class for MessageContextDialogSkill + """ + + def test_message_context_dialog_skill_serialization(self): + """ + Test serialization/deserialization for MessageContextDialogSkill + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + # Construct a json representation of a MessageContextDialogSkill model + message_context_dialog_skill_model_json = {} + message_context_dialog_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model_json['system'] = message_context_skill_system_model + + # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation + message_context_dialog_skill_model = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json) + assert message_context_dialog_skill_model != False - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation + message_context_dialog_skill_model_dict = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json).__dict__ + message_context_dialog_skill_model2 = MessageContextDialogSkill(**message_context_dialog_skill_model_dict) - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + # Verify the model instances are equivalent + assert message_context_dialog_skill_model == message_context_dialog_skill_model2 - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + # Convert model instance back to dict and verify no loss of data + message_context_dialog_skill_model_json2 = message_context_dialog_skill_model.to_dict() + assert message_context_dialog_skill_model_json2 == message_context_dialog_skill_model_json - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True +class TestModel_MessageContextGlobal: + """ + Test Class for MessageContextGlobal + """ - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['async_callout'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + def test_message_context_global_serialization(self): + """ + Test serialization/deserialization for MessageContextGlobal + """ - log_request_input_model = {} # LogRequestInput - log_request_input_model['message_type'] = 'text' - log_request_input_model['text'] = 'testString' - log_request_input_model['intents'] = [runtime_intent_model] - log_request_input_model['entities'] = [runtime_entity_model] - log_request_input_model['suggestion_id'] = 'testString' - log_request_input_model['attachments'] = [message_input_attachment_model] - log_request_input_model['analytics'] = request_analytics_model - log_request_input_model['options'] = message_input_options_model + # Construct dict forms of any model objects needed in order to build this model. message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' @@ -5104,186 +7990,159 @@ def test_log_collection_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + # Construct a json representation of a MessageContextGlobal model + message_context_global_model_json = {} + message_context_global_model_json['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) + assert message_context_global_model != False - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ + message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + # Verify the model instances are equivalent + assert message_context_global_model == message_context_global_model2 - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model + # Convert model instance back to dict and verify no loss of data + message_context_global_model_json2 = message_context_global_model.to_dict() + assert message_context_global_model_json2 == message_context_global_model_json - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} - log_request_model = {} # LogRequest - log_request_model['input'] = log_request_input_model - log_request_model['context'] = message_context_model - log_request_model['user_id'] = 'testString' +class TestModel_MessageContextGlobalSystem: + """ + Test Class for MessageContextGlobalSystem + """ - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + def test_message_context_global_system_serialization(self): + """ + Test serialization/deserialization for MessageContextGlobalSystem + """ - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + # Construct a json representation of a MessageContextGlobalSystem model + message_context_global_system_model_json = {} + message_context_global_system_model_json['timezone'] = 'testString' + message_context_global_system_model_json['user_id'] = 'testString' + message_context_global_system_model_json['turn_count'] = 38 + message_context_global_system_model_json['locale'] = 'en-us' + message_context_global_system_model_json['reference_time'] = 'testString' + message_context_global_system_model_json['session_start_time'] = 'testString' + message_context_global_system_model_json['state'] = 'testString' + message_context_global_system_model_json['skip_user_input'] = True - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) + assert message_context_global_system_model != False - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ + message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + # Verify the model instances are equivalent + assert message_context_global_system_model == message_context_global_system_model2 - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + # Convert model instance back to dict and verify no loss of data + message_context_global_system_model_json2 = message_context_global_system_model.to_dict() + assert message_context_global_system_model_json2 == message_context_global_system_model_json - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' +class TestModel_MessageContextSkillSystem: + """ + Test Class for MessageContextSkillSystem + """ - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + def test_message_context_skill_system_serialization(self): + """ + Test serialization/deserialization for MessageContextSkillSystem + """ - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' + # Construct a json representation of a MessageContextSkillSystem model + message_context_skill_system_model_json = {} + message_context_skill_system_model_json['state'] = 'testString' + message_context_skill_system_model_json['foo'] = 'testString' - log_response_output_model = {} # LogResponseOutput - log_response_output_model['generic'] = [runtime_response_generic_model] - log_response_output_model['intents'] = [runtime_intent_model] - log_response_output_model['entities'] = [runtime_entity_model] - log_response_output_model['actions'] = [dialog_node_action_model] - log_response_output_model['debug'] = message_output_debug_model - log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} - log_response_output_model['spelling'] = message_output_spelling_model + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) + assert message_context_skill_system_model != False - log_response_model = {} # LogResponse - log_response_model['output'] = log_response_output_model - log_response_model['context'] = message_context_model - log_response_model['user_id'] = 'testString' + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ + message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) - log_model = {} # Log - log_model['log_id'] = 'testString' - log_model['request'] = log_request_model - log_model['response'] = log_response_model - log_model['assistant_id'] = 'testString' - log_model['session_id'] = 'testString' - log_model['skill_id'] = 'testString' - log_model['snapshot'] = 'testString' - log_model['request_timestamp'] = 'testString' - log_model['response_timestamp'] = 'testString' - log_model['language'] = 'testString' - log_model['customer_id'] = 'testString' + # Verify the model instances are equivalent + assert message_context_skill_system_model == message_context_skill_system_model2 - log_pagination_model = {} # LogPagination - log_pagination_model['next_url'] = 'testString' - log_pagination_model['matched'] = 38 - log_pagination_model['next_cursor'] = 'testString' + # Convert model instance back to dict and verify no loss of data + message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() + assert message_context_skill_system_model_json2 == message_context_skill_system_model_json - # Construct a json representation of a LogCollection model - log_collection_model_json = {} - log_collection_model_json['logs'] = [log_model] - log_collection_model_json['pagination'] = log_pagination_model + # Test get_properties and set_properties methods. + message_context_skill_system_model.set_properties({}) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict == {} - # Construct a model instance of LogCollection by calling from_dict on the json representation - log_collection_model = LogCollection.from_dict(log_collection_model_json) - assert log_collection_model != False + expected_dict = {'foo': 'testString'} + message_context_skill_system_model.set_properties(expected_dict) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict.keys() == expected_dict.keys() - # Construct a model instance of LogCollection by calling from_dict on the json representation - log_collection_model_dict = LogCollection.from_dict(log_collection_model_json).__dict__ - log_collection_model2 = LogCollection(**log_collection_model_dict) - # Verify the model instances are equivalent - assert log_collection_model == log_collection_model2 +class TestModel_MessageContextSkills: + """ + Test Class for MessageContextSkills + """ - # Convert model instance back to dict and verify no loss of data - log_collection_model_json2 = log_collection_model.to_dict() - assert log_collection_model_json2 == log_collection_model_json + def test_message_context_skills_serialization(self): + """ + Test serialization/deserialization for MessageContextSkills + """ + + # Construct dict forms of any model objects needed in order to build this model. + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' -class TestModel_LogPagination: - """ - Test Class for LogPagination - """ + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - def test_log_pagination_serialization(self): - """ - Test serialization/deserialization for LogPagination - """ + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - # Construct a json representation of a LogPagination model - log_pagination_model_json = {} - log_pagination_model_json['next_url'] = 'testString' - log_pagination_model_json['matched'] = 38 - log_pagination_model_json['next_cursor'] = 'testString' + # Construct a json representation of a MessageContextSkills model + message_context_skills_model_json = {} + message_context_skills_model_json['main skill'] = message_context_dialog_skill_model + message_context_skills_model_json['actions skill'] = message_context_action_skill_model - # Construct a model instance of LogPagination by calling from_dict on the json representation - log_pagination_model = LogPagination.from_dict(log_pagination_model_json) - assert log_pagination_model != False + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) + assert message_context_skills_model != False - # Construct a model instance of LogPagination by calling from_dict on the json representation - log_pagination_model_dict = LogPagination.from_dict(log_pagination_model_json).__dict__ - log_pagination_model2 = LogPagination(**log_pagination_model_dict) + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ + message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) # Verify the model instances are equivalent - assert log_pagination_model == log_pagination_model2 + assert message_context_skills_model == message_context_skills_model2 # Convert model instance back to dict and verify no loss of data - log_pagination_model_json2 = log_pagination_model.to_dict() - assert log_pagination_model_json2 == log_pagination_model_json + message_context_skills_model_json2 = message_context_skills_model.to_dict() + assert message_context_skills_model_json2 == message_context_skills_model_json -class TestModel_LogRequest: +class TestModel_MessageInput: """ - Test Class for LogRequest + Test Class for MessageInput """ - def test_log_request_serialization(self): + def test_message_input_serialization(self): """ - Test serialization/deserialization for LogRequest + Test serialization/deserialization for MessageInput """ # Construct dict forms of any model objects needed in order to build this model. @@ -5362,201 +8221,148 @@ def test_log_request_serialization(self): message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False - log_request_input_model = {} # LogRequestInput - log_request_input_model['message_type'] = 'text' - log_request_input_model['text'] = 'Hello' - log_request_input_model['intents'] = [runtime_intent_model] - log_request_input_model['entities'] = [runtime_entity_model] - log_request_input_model['suggestion_id'] = 'testString' - log_request_input_model['attachments'] = [message_input_attachment_model] - log_request_input_model['analytics'] = request_analytics_model - log_request_input_model['options'] = message_input_options_model + # Construct a json representation of a MessageInput model + message_input_model_json = {} + message_input_model_json['message_type'] = 'text' + message_input_model_json['text'] = 'testString' + message_input_model_json['intents'] = [runtime_intent_model] + message_input_model_json['entities'] = [runtime_entity_model] + message_input_model_json['suggestion_id'] = 'testString' + message_input_model_json['attachments'] = [message_input_attachment_model] + message_input_model_json['analytics'] = request_analytics_model + message_input_model_json['options'] = message_input_options_model - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'my_user_id' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model = MessageInput.from_dict(message_input_model_json) + assert message_input_model != False - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ + message_input_model2 = MessageInput(**message_input_model_dict) - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Verify the model instances are equivalent + assert message_input_model == message_input_model2 - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Convert model instance back to dict and verify no loss of data + message_input_model_json2 = message_input_model.to_dict() + assert message_input_model_json2 == message_input_model_json - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model +class TestModel_MessageInputAttachment: + """ + Test Class for MessageInputAttachment + """ - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} + def test_message_input_attachment_serialization(self): + """ + Test serialization/deserialization for MessageInputAttachment + """ - # Construct a json representation of a LogRequest model - log_request_model_json = {} - log_request_model_json['input'] = log_request_input_model - log_request_model_json['context'] = message_context_model - log_request_model_json['user_id'] = 'testString' + # Construct a json representation of a MessageInputAttachment model + message_input_attachment_model_json = {} + message_input_attachment_model_json['url'] = 'testString' + message_input_attachment_model_json['media_type'] = 'testString' - # Construct a model instance of LogRequest by calling from_dict on the json representation - log_request_model = LogRequest.from_dict(log_request_model_json) - assert log_request_model != False + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) + assert message_input_attachment_model != False - # Construct a model instance of LogRequest by calling from_dict on the json representation - log_request_model_dict = LogRequest.from_dict(log_request_model_json).__dict__ - log_request_model2 = LogRequest(**log_request_model_dict) + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ + message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) # Verify the model instances are equivalent - assert log_request_model == log_request_model2 + assert message_input_attachment_model == message_input_attachment_model2 # Convert model instance back to dict and verify no loss of data - log_request_model_json2 = log_request_model.to_dict() - assert log_request_model_json2 == log_request_model_json + message_input_attachment_model_json2 = message_input_attachment_model.to_dict() + assert message_input_attachment_model_json2 == message_input_attachment_model_json -class TestModel_LogRequestInput: +class TestModel_MessageInputOptions: """ - Test Class for LogRequestInput + Test Class for MessageInputOptions """ - def test_log_request_input_serialization(self): + def test_message_input_options_serialization(self): """ - Test serialization/deserialization for LogRequestInput + Test serialization/deserialization for MessageInputOptions """ # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Construct a json representation of a MessageInputOptions model + message_input_options_model_json = {} + message_input_options_model_json['restart'] = False + message_input_options_model_json['alternate_intents'] = False + message_input_options_model_json['async_callout'] = False + message_input_options_model_json['spelling'] = message_input_options_spelling_model + message_input_options_model_json['debug'] = False + message_input_options_model_json['return_context'] = False + message_input_options_model_json['export'] = False - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) + assert message_input_options_model != False - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ + message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + # Verify the model instances are equivalent + assert message_input_options_model == message_input_options_model2 - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + # Convert model instance back to dict and verify no loss of data + message_input_options_model_json2 = message_input_options_model.to_dict() + assert message_input_options_model_json2 == message_input_options_model_json - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True +class TestModel_MessageInputOptionsSpelling: + """ + Test Class for MessageInputOptionsSpelling + """ - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['async_callout'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + def test_message_input_options_spelling_serialization(self): + """ + Test serialization/deserialization for MessageInputOptionsSpelling + """ - # Construct a json representation of a LogRequestInput model - log_request_input_model_json = {} - log_request_input_model_json['message_type'] = 'text' - log_request_input_model_json['text'] = 'testString' - log_request_input_model_json['intents'] = [runtime_intent_model] - log_request_input_model_json['entities'] = [runtime_entity_model] - log_request_input_model_json['suggestion_id'] = 'testString' - log_request_input_model_json['attachments'] = [message_input_attachment_model] - log_request_input_model_json['analytics'] = request_analytics_model - log_request_input_model_json['options'] = message_input_options_model + # Construct a json representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model_json = {} + message_input_options_spelling_model_json['suggestions'] = True + message_input_options_spelling_model_json['auto_correct'] = True - # Construct a model instance of LogRequestInput by calling from_dict on the json representation - log_request_input_model = LogRequestInput.from_dict(log_request_input_model_json) - assert log_request_input_model != False + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) + assert message_input_options_spelling_model != False - # Construct a model instance of LogRequestInput by calling from_dict on the json representation - log_request_input_model_dict = LogRequestInput.from_dict(log_request_input_model_json).__dict__ - log_request_input_model2 = LogRequestInput(**log_request_input_model_dict) + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ + message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) # Verify the model instances are equivalent - assert log_request_input_model == log_request_input_model2 + assert message_input_options_spelling_model == message_input_options_spelling_model2 # Convert model instance back to dict and verify no loss of data - log_request_input_model_json2 = log_request_input_model.to_dict() - assert log_request_input_model_json2 == log_request_input_model_json + message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() + assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json -class TestModel_LogResponse: +class TestModel_MessageOutput: """ - Test Class for LogResponse + Test Class for MessageOutput """ - def test_log_response_serialization(self): + def test_message_output_serialization(self): """ - Test serialization/deserialization for LogResponse + Test serialization/deserialization for MessageOutput """ # Construct dict forms of any model objects needed in order to build this model. @@ -5672,1029 +8478,1053 @@ def test_log_response_serialization(self): message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - log_response_output_model = {} # LogResponseOutput - log_response_output_model['generic'] = [runtime_response_generic_model] - log_response_output_model['intents'] = [runtime_intent_model] - log_response_output_model['entities'] = [runtime_entity_model] - log_response_output_model['actions'] = [dialog_node_action_model] - log_response_output_model['debug'] = message_output_debug_model - log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} - log_response_output_model['spelling'] = message_output_spelling_model + # Construct a json representation of a MessageOutput model + message_output_model_json = {} + message_output_model_json['generic'] = [runtime_response_generic_model] + message_output_model_json['intents'] = [runtime_intent_model] + message_output_model_json['entities'] = [runtime_entity_model] + message_output_model_json['actions'] = [dialog_node_action_model] + message_output_model_json['debug'] = message_output_debug_model + message_output_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_output_model_json['spelling'] = message_output_spelling_model - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model = MessageOutput.from_dict(message_output_model_json) + assert message_output_model != False - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model_dict = MessageOutput.from_dict(message_output_model_json).__dict__ + message_output_model2 = MessageOutput(**message_output_model_dict) - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Verify the model instances are equivalent + assert message_output_model == message_output_model2 - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Convert model instance back to dict and verify no loss of data + message_output_model_json2 = message_output_model.to_dict() + assert message_output_model_json2 == message_output_model_json - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model +class TestModel_MessageOutputDebug: + """ + Test Class for MessageOutputDebug + """ - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} + def test_message_output_debug_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebug + """ - # Construct a json representation of a LogResponse model - log_response_model_json = {} - log_response_model_json['output'] = log_response_output_model - log_response_model_json['context'] = message_context_model - log_response_model_json['user_id'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of LogResponse by calling from_dict on the json representation - log_response_model = LogResponse.from_dict(log_response_model_json) - assert log_response_model != False + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - # Construct a model instance of LogResponse by calling from_dict on the json representation - log_response_model_dict = LogResponse.from_dict(log_response_model_json).__dict__ - log_response_model2 = LogResponse(**log_response_model_dict) + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + # Construct a json representation of a MessageOutputDebug model + message_output_debug_model_json = {} + message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model_json['log_messages'] = [dialog_log_message_model] + message_output_debug_model_json['branch_exited'] = True + message_output_debug_model_json['branch_exited_reason'] = 'completed' + message_output_debug_model_json['turn_events'] = [message_output_debug_turn_event_model] + + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) + assert message_output_debug_model != False + + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model_dict = MessageOutputDebug.from_dict(message_output_debug_model_json).__dict__ + message_output_debug_model2 = MessageOutputDebug(**message_output_debug_model_dict) # Verify the model instances are equivalent - assert log_response_model == log_response_model2 + assert message_output_debug_model == message_output_debug_model2 # Convert model instance back to dict and verify no loss of data - log_response_model_json2 = log_response_model.to_dict() - assert log_response_model_json2 == log_response_model_json + message_output_debug_model_json2 = message_output_debug_model.to_dict() + assert message_output_debug_model_json2 == message_output_debug_model_json -class TestModel_LogResponseOutput: +class TestModel_MessageOutputSpelling: """ - Test Class for LogResponseOutput + Test Class for MessageOutputSpelling """ - def test_log_response_output_serialization(self): + def test_message_output_spelling_serialization(self): """ - Test serialization/deserialization for LogResponseOutput + Test serialization/deserialization for MessageOutputSpelling """ - # Construct dict forms of any model objects needed in order to build this model. - - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + # Construct a json representation of a MessageOutputSpelling model + message_output_spelling_model_json = {} + message_output_spelling_model_json['text'] = 'testString' + message_output_spelling_model_json['original_text'] = 'testString' + message_output_spelling_model_json['suggested_text'] = 'testString' - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model = MessageOutputSpelling.from_dict(message_output_spelling_model_json) + assert message_output_spelling_model != False - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model_dict = MessageOutputSpelling.from_dict(message_output_spelling_model_json).__dict__ + message_output_spelling_model2 = MessageOutputSpelling(**message_output_spelling_model_dict) - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Verify the model instances are equivalent + assert message_output_spelling_model == message_output_spelling_model2 - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Convert model instance back to dict and verify no loss of data + message_output_spelling_model_json2 = message_output_spelling_model.to_dict() + assert message_output_spelling_model_json2 == message_output_spelling_model_json - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' +class TestModel_Metadata: + """ + Test Class for Metadata + """ - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' + def test_metadata_serialization(self): + """ + Test serialization/deserialization for Metadata + """ - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + # Construct a json representation of a Metadata model + metadata_model_json = {} + metadata_model_json['id'] = 38 - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + # Construct a model instance of Metadata by calling from_dict on the json representation + metadata_model = Metadata.from_dict(metadata_model_json) + assert metadata_model != False - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + # Construct a model instance of Metadata by calling from_dict on the json representation + metadata_model_dict = Metadata.from_dict(metadata_model_json).__dict__ + metadata_model2 = Metadata(**metadata_model_dict) - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' + # Verify the model instances are equivalent + assert metadata_model == metadata_model2 - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' + # Convert model instance back to dict and verify no loss of data + metadata_model_json2 = metadata_model.to_dict() + assert metadata_model_json2 == metadata_model_json - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' +class TestModel_MonitorAssistantReleaseImportArtifactResponse: + """ + Test Class for MonitorAssistantReleaseImportArtifactResponse + """ - # Construct a json representation of a LogResponseOutput model - log_response_output_model_json = {} - log_response_output_model_json['generic'] = [runtime_response_generic_model] - log_response_output_model_json['intents'] = [runtime_intent_model] - log_response_output_model_json['entities'] = [runtime_entity_model] - log_response_output_model_json['actions'] = [dialog_node_action_model] - log_response_output_model_json['debug'] = message_output_debug_model - log_response_output_model_json['user_defined'] = {'anyKey': 'anyValue'} - log_response_output_model_json['spelling'] = message_output_spelling_model + def test_monitor_assistant_release_import_artifact_response_serialization(self): + """ + Test serialization/deserialization for MonitorAssistantReleaseImportArtifactResponse + """ - # Construct a model instance of LogResponseOutput by calling from_dict on the json representation - log_response_output_model = LogResponseOutput.from_dict(log_response_output_model_json) - assert log_response_output_model != False + # Construct a json representation of a MonitorAssistantReleaseImportArtifactResponse model + monitor_assistant_release_import_artifact_response_model_json = {} + monitor_assistant_release_import_artifact_response_model_json['skill_impact_in_draft'] = ['action'] - # Construct a model instance of LogResponseOutput by calling from_dict on the json representation - log_response_output_model_dict = LogResponseOutput.from_dict(log_response_output_model_json).__dict__ - log_response_output_model2 = LogResponseOutput(**log_response_output_model_dict) + # Construct a model instance of MonitorAssistantReleaseImportArtifactResponse by calling from_dict on the json representation + monitor_assistant_release_import_artifact_response_model = MonitorAssistantReleaseImportArtifactResponse.from_dict(monitor_assistant_release_import_artifact_response_model_json) + assert monitor_assistant_release_import_artifact_response_model != False + + # Construct a model instance of MonitorAssistantReleaseImportArtifactResponse by calling from_dict on the json representation + monitor_assistant_release_import_artifact_response_model_dict = MonitorAssistantReleaseImportArtifactResponse.from_dict(monitor_assistant_release_import_artifact_response_model_json).__dict__ + monitor_assistant_release_import_artifact_response_model2 = MonitorAssistantReleaseImportArtifactResponse(**monitor_assistant_release_import_artifact_response_model_dict) # Verify the model instances are equivalent - assert log_response_output_model == log_response_output_model2 + assert monitor_assistant_release_import_artifact_response_model == monitor_assistant_release_import_artifact_response_model2 # Convert model instance back to dict and verify no loss of data - log_response_output_model_json2 = log_response_output_model.to_dict() - assert log_response_output_model_json2 == log_response_output_model_json + monitor_assistant_release_import_artifact_response_model_json2 = monitor_assistant_release_import_artifact_response_model.to_dict() + assert monitor_assistant_release_import_artifact_response_model_json2 == monitor_assistant_release_import_artifact_response_model_json -class TestModel_MessageContext: +class TestModel_Pagination: """ - Test Class for MessageContext + Test Class for Pagination """ - def test_message_context_serialization(self): + def test_pagination_serialization(self): """ - Test serialization/deserialization for MessageContext + Test serialization/deserialization for Pagination """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a Pagination model + pagination_model_json = {} + pagination_model_json['refresh_url'] = 'testString' + pagination_model_json['next_url'] = 'testString' + pagination_model_json['total'] = 38 + pagination_model_json['matched'] = 38 + pagination_model_json['refresh_cursor'] = 'testString' + pagination_model_json['next_cursor'] = 'testString' - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model = Pagination.from_dict(pagination_model_json) + assert pagination_model != False - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ + pagination_model2 = Pagination(**pagination_model_dict) - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Verify the model instances are equivalent + assert pagination_model == pagination_model2 - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Convert model instance back to dict and verify no loss of data + pagination_model_json2 = pagination_model.to_dict() + assert pagination_model_json2 == pagination_model_json - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model +class TestModel_ProviderAuthenticationOAuth2: + """ + Test Class for ProviderAuthenticationOAuth2 + """ - # Construct a json representation of a MessageContext model - message_context_model_json = {} - message_context_model_json['global'] = message_context_global_model - message_context_model_json['skills'] = message_context_skills_model - message_context_model_json['integrations'] = {'anyKey': 'anyValue'} + def test_provider_authentication_o_auth2_serialization(self): + """ + Test serialization/deserialization for ProviderAuthenticationOAuth2 + """ - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model = MessageContext.from_dict(message_context_model_json) - assert message_context_model != False + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ - message_context_model2 = MessageContext(**message_context_model_dict) + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a json representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model_json = {} + provider_authentication_o_auth2_model_json['preferred_flow'] = 'password' + provider_authentication_o_auth2_model_json['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a model instance of ProviderAuthenticationOAuth2 by calling from_dict on the json representation + provider_authentication_o_auth2_model = ProviderAuthenticationOAuth2.from_dict(provider_authentication_o_auth2_model_json) + assert provider_authentication_o_auth2_model != False + + # Construct a model instance of ProviderAuthenticationOAuth2 by calling from_dict on the json representation + provider_authentication_o_auth2_model_dict = ProviderAuthenticationOAuth2.from_dict(provider_authentication_o_auth2_model_json).__dict__ + provider_authentication_o_auth2_model2 = ProviderAuthenticationOAuth2(**provider_authentication_o_auth2_model_dict) # Verify the model instances are equivalent - assert message_context_model == message_context_model2 + assert provider_authentication_o_auth2_model == provider_authentication_o_auth2_model2 # Convert model instance back to dict and verify no loss of data - message_context_model_json2 = message_context_model.to_dict() - assert message_context_model_json2 == message_context_model_json + provider_authentication_o_auth2_model_json2 = provider_authentication_o_auth2_model.to_dict() + assert provider_authentication_o_auth2_model_json2 == provider_authentication_o_auth2_model_json -class TestModel_MessageContextActionSkill: +class TestModel_ProviderAuthenticationOAuth2PasswordUsername: """ - Test Class for MessageContextActionSkill + Test Class for ProviderAuthenticationOAuth2PasswordUsername """ - def test_message_context_action_skill_serialization(self): + def test_provider_authentication_o_auth2_password_username_serialization(self): """ - Test serialization/deserialization for MessageContextActionSkill + Test serialization/deserialization for ProviderAuthenticationOAuth2PasswordUsername """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model_json = {} + provider_authentication_o_auth2_password_username_model_json['type'] = 'value' + provider_authentication_o_auth2_password_username_model_json['value'] = 'testString' - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Construct a model instance of ProviderAuthenticationOAuth2PasswordUsername by calling from_dict on the json representation + provider_authentication_o_auth2_password_username_model = ProviderAuthenticationOAuth2PasswordUsername.from_dict(provider_authentication_o_auth2_password_username_model_json) + assert provider_authentication_o_auth2_password_username_model != False - # Construct a json representation of a MessageContextActionSkill model - message_context_action_skill_model_json = {} - message_context_action_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model_json['system'] = message_context_skill_system_model - message_context_action_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} + # Construct a model instance of ProviderAuthenticationOAuth2PasswordUsername by calling from_dict on the json representation + provider_authentication_o_auth2_password_username_model_dict = ProviderAuthenticationOAuth2PasswordUsername.from_dict(provider_authentication_o_auth2_password_username_model_json).__dict__ + provider_authentication_o_auth2_password_username_model2 = ProviderAuthenticationOAuth2PasswordUsername(**provider_authentication_o_auth2_password_username_model_dict) - # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation - message_context_action_skill_model = MessageContextActionSkill.from_dict(message_context_action_skill_model_json) - assert message_context_action_skill_model != False + # Verify the model instances are equivalent + assert provider_authentication_o_auth2_password_username_model == provider_authentication_o_auth2_password_username_model2 + + # Convert model instance back to dict and verify no loss of data + provider_authentication_o_auth2_password_username_model_json2 = provider_authentication_o_auth2_password_username_model.to_dict() + assert provider_authentication_o_auth2_password_username_model_json2 == provider_authentication_o_auth2_password_username_model_json - # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation - message_context_action_skill_model_dict = MessageContextActionSkill.from_dict(message_context_action_skill_model_json).__dict__ - message_context_action_skill_model2 = MessageContextActionSkill(**message_context_action_skill_model_dict) + +class TestModel_ProviderAuthenticationTypeAndValue: + """ + Test Class for ProviderAuthenticationTypeAndValue + """ + + def test_provider_authentication_type_and_value_serialization(self): + """ + Test serialization/deserialization for ProviderAuthenticationTypeAndValue + """ + + # Construct a json representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model_json = {} + provider_authentication_type_and_value_model_json['type'] = 'value' + provider_authentication_type_and_value_model_json['value'] = 'testString' + + # Construct a model instance of ProviderAuthenticationTypeAndValue by calling from_dict on the json representation + provider_authentication_type_and_value_model = ProviderAuthenticationTypeAndValue.from_dict(provider_authentication_type_and_value_model_json) + assert provider_authentication_type_and_value_model != False + + # Construct a model instance of ProviderAuthenticationTypeAndValue by calling from_dict on the json representation + provider_authentication_type_and_value_model_dict = ProviderAuthenticationTypeAndValue.from_dict(provider_authentication_type_and_value_model_json).__dict__ + provider_authentication_type_and_value_model2 = ProviderAuthenticationTypeAndValue(**provider_authentication_type_and_value_model_dict) # Verify the model instances are equivalent - assert message_context_action_skill_model == message_context_action_skill_model2 + assert provider_authentication_type_and_value_model == provider_authentication_type_and_value_model2 # Convert model instance back to dict and verify no loss of data - message_context_action_skill_model_json2 = message_context_action_skill_model.to_dict() - assert message_context_action_skill_model_json2 == message_context_action_skill_model_json + provider_authentication_type_and_value_model_json2 = provider_authentication_type_and_value_model.to_dict() + assert provider_authentication_type_and_value_model_json2 == provider_authentication_type_and_value_model_json -class TestModel_MessageContextDialogSkill: +class TestModel_ProviderCollection: """ - Test Class for MessageContextDialogSkill + Test Class for ProviderCollection """ - def test_message_context_dialog_skill_serialization(self): + def test_provider_collection_serialization(self): """ - Test serialization/deserialization for MessageContextDialogSkill + Test serialization/deserialization for ProviderCollection """ # Construct dict forms of any model objects needed in order to build this model. - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem + provider_response_specification_servers_item_model['url'] = 'testString' - # Construct a json representation of a MessageContextDialogSkill model - message_context_dialog_skill_model_json = {} - message_context_dialog_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model_json['system'] = message_context_skill_system_model + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation - message_context_dialog_skill_model = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json) - assert message_context_dialog_skill_model != False + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation - message_context_dialog_skill_model_dict = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json).__dict__ - message_context_dialog_skill_model2 = MessageContextDialogSkill(**message_context_dialog_skill_model_dict) + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents + provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model + + provider_response_specification_model = {} # ProviderResponseSpecification + provider_response_specification_model['servers'] = [provider_response_specification_servers_item_model] + provider_response_specification_model['components'] = provider_response_specification_components_model + + provider_response_model = {} # ProviderResponse + provider_response_model['provider_id'] = 'testString' + provider_response_model['specification'] = provider_response_specification_model + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a ProviderCollection model + provider_collection_model_json = {} + provider_collection_model_json['conversational_skill_providers'] = [provider_response_model] + provider_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of ProviderCollection by calling from_dict on the json representation + provider_collection_model = ProviderCollection.from_dict(provider_collection_model_json) + assert provider_collection_model != False + + # Construct a model instance of ProviderCollection by calling from_dict on the json representation + provider_collection_model_dict = ProviderCollection.from_dict(provider_collection_model_json).__dict__ + provider_collection_model2 = ProviderCollection(**provider_collection_model_dict) # Verify the model instances are equivalent - assert message_context_dialog_skill_model == message_context_dialog_skill_model2 + assert provider_collection_model == provider_collection_model2 # Convert model instance back to dict and verify no loss of data - message_context_dialog_skill_model_json2 = message_context_dialog_skill_model.to_dict() - assert message_context_dialog_skill_model_json2 == message_context_dialog_skill_model_json + provider_collection_model_json2 = provider_collection_model.to_dict() + assert provider_collection_model_json2 == provider_collection_model_json -class TestModel_MessageContextGlobal: +class TestModel_ProviderPrivate: """ - Test Class for MessageContextGlobal + Test Class for ProviderPrivate """ - def test_message_context_global_serialization(self): + def test_provider_private_serialization(self): """ - Test serialization/deserialization for MessageContextGlobal + Test serialization/deserialization for ProviderPrivate """ # Construct dict forms of any model objects needed in order to build this model. - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a json representation of a MessageContextGlobal model - message_context_global_model_json = {} - message_context_global_model_json['system'] = message_context_global_system_model + provider_private_authentication_model = {} # ProviderPrivateAuthenticationBearerFlow + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) - assert message_context_global_model != False + # Construct a json representation of a ProviderPrivate model + provider_private_model_json = {} + provider_private_model_json['authentication'] = provider_private_authentication_model - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ - message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) + # Construct a model instance of ProviderPrivate by calling from_dict on the json representation + provider_private_model = ProviderPrivate.from_dict(provider_private_model_json) + assert provider_private_model != False + + # Construct a model instance of ProviderPrivate by calling from_dict on the json representation + provider_private_model_dict = ProviderPrivate.from_dict(provider_private_model_json).__dict__ + provider_private_model2 = ProviderPrivate(**provider_private_model_dict) # Verify the model instances are equivalent - assert message_context_global_model == message_context_global_model2 + assert provider_private_model == provider_private_model2 # Convert model instance back to dict and verify no loss of data - message_context_global_model_json2 = message_context_global_model.to_dict() - assert message_context_global_model_json2 == message_context_global_model_json + provider_private_model_json2 = provider_private_model.to_dict() + assert provider_private_model_json2 == provider_private_model_json -class TestModel_MessageContextGlobalSystem: +class TestModel_ProviderPrivateAuthenticationOAuth2PasswordPassword: """ - Test Class for MessageContextGlobalSystem + Test Class for ProviderPrivateAuthenticationOAuth2PasswordPassword """ - def test_message_context_global_system_serialization(self): + def test_provider_private_authentication_o_auth2_password_password_serialization(self): """ - Test serialization/deserialization for MessageContextGlobalSystem + Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2PasswordPassword """ - # Construct a json representation of a MessageContextGlobalSystem model - message_context_global_system_model_json = {} - message_context_global_system_model_json['timezone'] = 'testString' - message_context_global_system_model_json['user_id'] = 'testString' - message_context_global_system_model_json['turn_count'] = 38 - message_context_global_system_model_json['locale'] = 'en-us' - message_context_global_system_model_json['reference_time'] = 'testString' - message_context_global_system_model_json['session_start_time'] = 'testString' - message_context_global_system_model_json['state'] = 'testString' - message_context_global_system_model_json['skip_user_input'] = True + # Construct a json representation of a ProviderPrivateAuthenticationOAuth2PasswordPassword model + provider_private_authentication_o_auth2_password_password_model_json = {} + provider_private_authentication_o_auth2_password_password_model_json['type'] = 'value' + provider_private_authentication_o_auth2_password_password_model_json['value'] = 'testString' - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) - assert message_context_global_system_model != False + # Construct a model instance of ProviderPrivateAuthenticationOAuth2PasswordPassword by calling from_dict on the json representation + provider_private_authentication_o_auth2_password_password_model = ProviderPrivateAuthenticationOAuth2PasswordPassword.from_dict(provider_private_authentication_o_auth2_password_password_model_json) + assert provider_private_authentication_o_auth2_password_password_model != False - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ - message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) + # Construct a model instance of ProviderPrivateAuthenticationOAuth2PasswordPassword by calling from_dict on the json representation + provider_private_authentication_o_auth2_password_password_model_dict = ProviderPrivateAuthenticationOAuth2PasswordPassword.from_dict(provider_private_authentication_o_auth2_password_password_model_json).__dict__ + provider_private_authentication_o_auth2_password_password_model2 = ProviderPrivateAuthenticationOAuth2PasswordPassword(**provider_private_authentication_o_auth2_password_password_model_dict) # Verify the model instances are equivalent - assert message_context_global_system_model == message_context_global_system_model2 + assert provider_private_authentication_o_auth2_password_password_model == provider_private_authentication_o_auth2_password_password_model2 # Convert model instance back to dict and verify no loss of data - message_context_global_system_model_json2 = message_context_global_system_model.to_dict() - assert message_context_global_system_model_json2 == message_context_global_system_model_json + provider_private_authentication_o_auth2_password_password_model_json2 = provider_private_authentication_o_auth2_password_password_model.to_dict() + assert provider_private_authentication_o_auth2_password_password_model_json2 == provider_private_authentication_o_auth2_password_password_model_json -class TestModel_MessageContextSkillSystem: +class TestModel_ProviderResponse: """ - Test Class for MessageContextSkillSystem + Test Class for ProviderResponse """ - def test_message_context_skill_system_serialization(self): + def test_provider_response_serialization(self): """ - Test serialization/deserialization for MessageContextSkillSystem + Test serialization/deserialization for ProviderResponse """ - # Construct a json representation of a MessageContextSkillSystem model - message_context_skill_system_model_json = {} - message_context_skill_system_model_json['state'] = 'testString' - message_context_skill_system_model_json['foo'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) - assert message_context_skill_system_model != False + provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem + provider_response_specification_servers_item_model['url'] = 'testString' - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ - message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Verify the model instances are equivalent - assert message_context_skill_system_model == message_context_skill_system_model2 + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - # Convert model instance back to dict and verify no loss of data - message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() - assert message_context_skill_system_model_json2 == message_context_skill_system_model_json + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - # Test get_properties and set_properties methods. - message_context_skill_system_model.set_properties({}) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict == {} + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - expected_dict = {'foo': 'testString'} - message_context_skill_system_model.set_properties(expected_dict) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict == expected_dict + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model -class TestModel_MessageContextSkills: + provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents + provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model + + provider_response_specification_model = {} # ProviderResponseSpecification + provider_response_specification_model['servers'] = [provider_response_specification_servers_item_model] + provider_response_specification_model['components'] = provider_response_specification_components_model + + # Construct a json representation of a ProviderResponse model + provider_response_model_json = {} + provider_response_model_json['provider_id'] = 'testString' + provider_response_model_json['specification'] = provider_response_specification_model + + # Construct a model instance of ProviderResponse by calling from_dict on the json representation + provider_response_model = ProviderResponse.from_dict(provider_response_model_json) + assert provider_response_model != False + + # Construct a model instance of ProviderResponse by calling from_dict on the json representation + provider_response_model_dict = ProviderResponse.from_dict(provider_response_model_json).__dict__ + provider_response_model2 = ProviderResponse(**provider_response_model_dict) + + # Verify the model instances are equivalent + assert provider_response_model == provider_response_model2 + + # Convert model instance back to dict and verify no loss of data + provider_response_model_json2 = provider_response_model.to_dict() + assert provider_response_model_json2 == provider_response_model_json + + +class TestModel_ProviderResponseSpecification: """ - Test Class for MessageContextSkills + Test Class for ProviderResponseSpecification """ - def test_message_context_skills_serialization(self): + def test_provider_response_specification_serialization(self): """ - Test serialization/deserialization for MessageContextSkills + Test serialization/deserialization for ProviderResponseSpecification """ # Construct dict forms of any model objects needed in order to build this model. - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem + provider_response_specification_servers_item_model['url'] = 'testString' - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - # Construct a json representation of a MessageContextSkills model - message_context_skills_model_json = {} - message_context_skills_model_json['main skill'] = message_context_dialog_skill_model - message_context_skills_model_json['actions skill'] = message_context_action_skill_model + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - # Construct a model instance of MessageContextSkills by calling from_dict on the json representation - message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) - assert message_context_skills_model != False + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - # Construct a model instance of MessageContextSkills by calling from_dict on the json representation - message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ - message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents + provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model + + # Construct a json representation of a ProviderResponseSpecification model + provider_response_specification_model_json = {} + provider_response_specification_model_json['servers'] = [provider_response_specification_servers_item_model] + provider_response_specification_model_json['components'] = provider_response_specification_components_model + + # Construct a model instance of ProviderResponseSpecification by calling from_dict on the json representation + provider_response_specification_model = ProviderResponseSpecification.from_dict(provider_response_specification_model_json) + assert provider_response_specification_model != False + + # Construct a model instance of ProviderResponseSpecification by calling from_dict on the json representation + provider_response_specification_model_dict = ProviderResponseSpecification.from_dict(provider_response_specification_model_json).__dict__ + provider_response_specification_model2 = ProviderResponseSpecification(**provider_response_specification_model_dict) # Verify the model instances are equivalent - assert message_context_skills_model == message_context_skills_model2 + assert provider_response_specification_model == provider_response_specification_model2 # Convert model instance back to dict and verify no loss of data - message_context_skills_model_json2 = message_context_skills_model.to_dict() - assert message_context_skills_model_json2 == message_context_skills_model_json + provider_response_specification_model_json2 = provider_response_specification_model.to_dict() + assert provider_response_specification_model_json2 == provider_response_specification_model_json -class TestModel_MessageInput: +class TestModel_ProviderResponseSpecificationComponents: """ - Test Class for MessageInput + Test Class for ProviderResponseSpecificationComponents """ - def test_message_input_serialization(self): + def test_provider_response_specification_components_serialization(self): """ - Test serialization/deserialization for MessageInput + Test serialization/deserialization for ProviderResponseSpecificationComponents """ # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' - - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 - - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['async_callout'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - # Construct a json representation of a MessageInput model - message_input_model_json = {} - message_input_model_json['message_type'] = 'text' - message_input_model_json['text'] = 'testString' - message_input_model_json['intents'] = [runtime_intent_model] - message_input_model_json['entities'] = [runtime_entity_model] - message_input_model_json['suggestion_id'] = 'testString' - message_input_model_json['attachments'] = [message_input_attachment_model] - message_input_model_json['analytics'] = request_analytics_model - message_input_model_json['options'] = message_input_options_model + # Construct a json representation of a ProviderResponseSpecificationComponents model + provider_response_specification_components_model_json = {} + provider_response_specification_components_model_json['securitySchemes'] = provider_response_specification_components_security_schemes_model - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model = MessageInput.from_dict(message_input_model_json) - assert message_input_model != False + # Construct a model instance of ProviderResponseSpecificationComponents by calling from_dict on the json representation + provider_response_specification_components_model = ProviderResponseSpecificationComponents.from_dict(provider_response_specification_components_model_json) + assert provider_response_specification_components_model != False - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ - message_input_model2 = MessageInput(**message_input_model_dict) + # Construct a model instance of ProviderResponseSpecificationComponents by calling from_dict on the json representation + provider_response_specification_components_model_dict = ProviderResponseSpecificationComponents.from_dict(provider_response_specification_components_model_json).__dict__ + provider_response_specification_components_model2 = ProviderResponseSpecificationComponents(**provider_response_specification_components_model_dict) # Verify the model instances are equivalent - assert message_input_model == message_input_model2 + assert provider_response_specification_components_model == provider_response_specification_components_model2 # Convert model instance back to dict and verify no loss of data - message_input_model_json2 = message_input_model.to_dict() - assert message_input_model_json2 == message_input_model_json + provider_response_specification_components_model_json2 = provider_response_specification_components_model.to_dict() + assert provider_response_specification_components_model_json2 == provider_response_specification_components_model_json -class TestModel_MessageInputAttachment: +class TestModel_ProviderResponseSpecificationComponentsSecuritySchemes: """ - Test Class for MessageInputAttachment + Test Class for ProviderResponseSpecificationComponentsSecuritySchemes """ - def test_message_input_attachment_serialization(self): + def test_provider_response_specification_components_security_schemes_serialization(self): """ - Test serialization/deserialization for MessageInputAttachment + Test serialization/deserialization for ProviderResponseSpecificationComponentsSecuritySchemes """ - # Construct a json representation of a MessageInputAttachment model - message_input_attachment_model_json = {} - message_input_attachment_model_json['url'] = 'testString' - message_input_attachment_model_json['media_type'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) - assert message_input_attachment_model != False + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ - message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a json representation of a ProviderResponseSpecificationComponentsSecuritySchemes model + provider_response_specification_components_security_schemes_model_json = {} + provider_response_specification_components_security_schemes_model_json['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model_json['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model_json['oauth2'] = provider_authentication_o_auth2_model + + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_response_specification_components_security_schemes_model = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict(provider_response_specification_components_security_schemes_model_json) + assert provider_response_specification_components_security_schemes_model != False + + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_response_specification_components_security_schemes_model_dict = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict(provider_response_specification_components_security_schemes_model_json).__dict__ + provider_response_specification_components_security_schemes_model2 = ProviderResponseSpecificationComponentsSecuritySchemes(**provider_response_specification_components_security_schemes_model_dict) # Verify the model instances are equivalent - assert message_input_attachment_model == message_input_attachment_model2 + assert provider_response_specification_components_security_schemes_model == provider_response_specification_components_security_schemes_model2 # Convert model instance back to dict and verify no loss of data - message_input_attachment_model_json2 = message_input_attachment_model.to_dict() - assert message_input_attachment_model_json2 == message_input_attachment_model_json + provider_response_specification_components_security_schemes_model_json2 = provider_response_specification_components_security_schemes_model.to_dict() + assert provider_response_specification_components_security_schemes_model_json2 == provider_response_specification_components_security_schemes_model_json -class TestModel_MessageInputOptions: +class TestModel_ProviderResponseSpecificationComponentsSecuritySchemesBasic: """ - Test Class for MessageInputOptions + Test Class for ProviderResponseSpecificationComponentsSecuritySchemesBasic """ - def test_message_input_options_serialization(self): + def test_provider_response_specification_components_security_schemes_basic_serialization(self): """ - Test serialization/deserialization for MessageInputOptions + Test serialization/deserialization for ProviderResponseSpecificationComponentsSecuritySchemesBasic """ # Construct dict forms of any model objects needed in order to build this model. - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a json representation of a MessageInputOptions model - message_input_options_model_json = {} - message_input_options_model_json['restart'] = False - message_input_options_model_json['alternate_intents'] = False - message_input_options_model_json['async_callout'] = False - message_input_options_model_json['spelling'] = message_input_options_spelling_model - message_input_options_model_json['debug'] = False - message_input_options_model_json['return_context'] = False - message_input_options_model_json['export'] = False + # Construct a json representation of a ProviderResponseSpecificationComponentsSecuritySchemesBasic model + provider_response_specification_components_security_schemes_basic_model_json = {} + provider_response_specification_components_security_schemes_basic_model_json['username'] = provider_authentication_type_and_value_model - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) - assert message_input_options_model != False + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_response_specification_components_security_schemes_basic_model = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict(provider_response_specification_components_security_schemes_basic_model_json) + assert provider_response_specification_components_security_schemes_basic_model != False - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ - message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_response_specification_components_security_schemes_basic_model_dict = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict(provider_response_specification_components_security_schemes_basic_model_json).__dict__ + provider_response_specification_components_security_schemes_basic_model2 = ProviderResponseSpecificationComponentsSecuritySchemesBasic(**provider_response_specification_components_security_schemes_basic_model_dict) # Verify the model instances are equivalent - assert message_input_options_model == message_input_options_model2 + assert provider_response_specification_components_security_schemes_basic_model == provider_response_specification_components_security_schemes_basic_model2 # Convert model instance back to dict and verify no loss of data - message_input_options_model_json2 = message_input_options_model.to_dict() - assert message_input_options_model_json2 == message_input_options_model_json + provider_response_specification_components_security_schemes_basic_model_json2 = provider_response_specification_components_security_schemes_basic_model.to_dict() + assert provider_response_specification_components_security_schemes_basic_model_json2 == provider_response_specification_components_security_schemes_basic_model_json -class TestModel_MessageInputOptionsSpelling: +class TestModel_ProviderResponseSpecificationServersItem: """ - Test Class for MessageInputOptionsSpelling + Test Class for ProviderResponseSpecificationServersItem """ - def test_message_input_options_spelling_serialization(self): + def test_provider_response_specification_servers_item_serialization(self): """ - Test serialization/deserialization for MessageInputOptionsSpelling + Test serialization/deserialization for ProviderResponseSpecificationServersItem """ - # Construct a json representation of a MessageInputOptionsSpelling model - message_input_options_spelling_model_json = {} - message_input_options_spelling_model_json['suggestions'] = True - message_input_options_spelling_model_json['auto_correct'] = True + # Construct a json representation of a ProviderResponseSpecificationServersItem model + provider_response_specification_servers_item_model_json = {} + provider_response_specification_servers_item_model_json['url'] = 'testString' - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) - assert message_input_options_spelling_model != False + # Construct a model instance of ProviderResponseSpecificationServersItem by calling from_dict on the json representation + provider_response_specification_servers_item_model = ProviderResponseSpecificationServersItem.from_dict(provider_response_specification_servers_item_model_json) + assert provider_response_specification_servers_item_model != False - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ - message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) + # Construct a model instance of ProviderResponseSpecificationServersItem by calling from_dict on the json representation + provider_response_specification_servers_item_model_dict = ProviderResponseSpecificationServersItem.from_dict(provider_response_specification_servers_item_model_json).__dict__ + provider_response_specification_servers_item_model2 = ProviderResponseSpecificationServersItem(**provider_response_specification_servers_item_model_dict) # Verify the model instances are equivalent - assert message_input_options_spelling_model == message_input_options_spelling_model2 + assert provider_response_specification_servers_item_model == provider_response_specification_servers_item_model2 # Convert model instance back to dict and verify no loss of data - message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() - assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json + provider_response_specification_servers_item_model_json2 = provider_response_specification_servers_item_model.to_dict() + assert provider_response_specification_servers_item_model_json2 == provider_response_specification_servers_item_model_json -class TestModel_MessageOutput: +class TestModel_ProviderSpecification: """ - Test Class for MessageOutput + Test Class for ProviderSpecification """ - def test_message_output_serialization(self): + def test_provider_specification_serialization(self): """ - Test serialization/deserialization for MessageOutput + Test serialization/deserialization for ProviderSpecification """ # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + provider_specification_servers_item_model = {} # ProviderSpecificationServersItem + provider_specification_servers_item_model['url'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + provider_specification_components_security_schemes_model = {} # ProviderSpecificationComponentsSecuritySchemes + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + provider_specification_components_model = {} # ProviderSpecificationComponents + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a json representation of a ProviderSpecification model + provider_specification_model_json = {} + provider_specification_model_json['servers'] = [provider_specification_servers_item_model] + provider_specification_model_json['components'] = provider_specification_components_model + + # Construct a model instance of ProviderSpecification by calling from_dict on the json representation + provider_specification_model = ProviderSpecification.from_dict(provider_specification_model_json) + assert provider_specification_model != False + + # Construct a model instance of ProviderSpecification by calling from_dict on the json representation + provider_specification_model_dict = ProviderSpecification.from_dict(provider_specification_model_json).__dict__ + provider_specification_model2 = ProviderSpecification(**provider_specification_model_dict) - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Verify the model instances are equivalent + assert provider_specification_model == provider_specification_model2 - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Convert model instance back to dict and verify no loss of data + provider_specification_model_json2 = provider_specification_model.to_dict() + assert provider_specification_model_json2 == provider_specification_model_json - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' +class TestModel_ProviderSpecificationComponents: + """ + Test Class for ProviderSpecificationComponents + """ - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' + def test_provider_specification_components_serialization(self): + """ + Test serialization/deserialization for ProviderSpecificationComponents + """ - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' + provider_specification_components_security_schemes_model = {} # ProviderSpecificationComponentsSecuritySchemes + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - # Construct a json representation of a MessageOutput model - message_output_model_json = {} - message_output_model_json['generic'] = [runtime_response_generic_model] - message_output_model_json['intents'] = [runtime_intent_model] - message_output_model_json['entities'] = [runtime_entity_model] - message_output_model_json['actions'] = [dialog_node_action_model] - message_output_model_json['debug'] = message_output_debug_model - message_output_model_json['user_defined'] = {'anyKey': 'anyValue'} - message_output_model_json['spelling'] = message_output_spelling_model + # Construct a json representation of a ProviderSpecificationComponents model + provider_specification_components_model_json = {} + provider_specification_components_model_json['securitySchemes'] = provider_specification_components_security_schemes_model - # Construct a model instance of MessageOutput by calling from_dict on the json representation - message_output_model = MessageOutput.from_dict(message_output_model_json) - assert message_output_model != False + # Construct a model instance of ProviderSpecificationComponents by calling from_dict on the json representation + provider_specification_components_model = ProviderSpecificationComponents.from_dict(provider_specification_components_model_json) + assert provider_specification_components_model != False - # Construct a model instance of MessageOutput by calling from_dict on the json representation - message_output_model_dict = MessageOutput.from_dict(message_output_model_json).__dict__ - message_output_model2 = MessageOutput(**message_output_model_dict) + # Construct a model instance of ProviderSpecificationComponents by calling from_dict on the json representation + provider_specification_components_model_dict = ProviderSpecificationComponents.from_dict(provider_specification_components_model_json).__dict__ + provider_specification_components_model2 = ProviderSpecificationComponents(**provider_specification_components_model_dict) # Verify the model instances are equivalent - assert message_output_model == message_output_model2 + assert provider_specification_components_model == provider_specification_components_model2 # Convert model instance back to dict and verify no loss of data - message_output_model_json2 = message_output_model.to_dict() - assert message_output_model_json2 == message_output_model_json + provider_specification_components_model_json2 = provider_specification_components_model.to_dict() + assert provider_specification_components_model_json2 == provider_specification_components_model_json -class TestModel_MessageOutputDebug: +class TestModel_ProviderSpecificationComponentsSecuritySchemes: """ - Test Class for MessageOutputDebug + Test Class for ProviderSpecificationComponentsSecuritySchemes """ - def test_message_output_debug_serialization(self): + def test_provider_specification_components_security_schemes_serialization(self): """ - Test serialization/deserialization for MessageOutputDebug + Test serialization/deserialization for ProviderSpecificationComponentsSecuritySchemes """ # Construct dict forms of any model objects needed in order to build this model. - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - # Construct a json representation of a MessageOutputDebug model - message_output_debug_model_json = {} - message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model_json['log_messages'] = [dialog_log_message_model] - message_output_debug_model_json['branch_exited'] = True - message_output_debug_model_json['branch_exited_reason'] = 'completed' - message_output_debug_model_json['turn_events'] = [message_output_debug_turn_event_model] + # Construct a json representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model_json = {} + provider_specification_components_security_schemes_model_json['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model_json['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model_json['oauth2'] = provider_authentication_o_auth2_model - # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation - message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) - assert message_output_debug_model != False + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_specification_components_security_schemes_model = ProviderSpecificationComponentsSecuritySchemes.from_dict(provider_specification_components_security_schemes_model_json) + assert provider_specification_components_security_schemes_model != False - # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation - message_output_debug_model_dict = MessageOutputDebug.from_dict(message_output_debug_model_json).__dict__ - message_output_debug_model2 = MessageOutputDebug(**message_output_debug_model_dict) + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_specification_components_security_schemes_model_dict = ProviderSpecificationComponentsSecuritySchemes.from_dict(provider_specification_components_security_schemes_model_json).__dict__ + provider_specification_components_security_schemes_model2 = ProviderSpecificationComponentsSecuritySchemes(**provider_specification_components_security_schemes_model_dict) # Verify the model instances are equivalent - assert message_output_debug_model == message_output_debug_model2 + assert provider_specification_components_security_schemes_model == provider_specification_components_security_schemes_model2 # Convert model instance back to dict and verify no loss of data - message_output_debug_model_json2 = message_output_debug_model.to_dict() - assert message_output_debug_model_json2 == message_output_debug_model_json + provider_specification_components_security_schemes_model_json2 = provider_specification_components_security_schemes_model.to_dict() + assert provider_specification_components_security_schemes_model_json2 == provider_specification_components_security_schemes_model_json -class TestModel_MessageOutputSpelling: +class TestModel_ProviderSpecificationComponentsSecuritySchemesBasic: """ - Test Class for MessageOutputSpelling + Test Class for ProviderSpecificationComponentsSecuritySchemesBasic """ - def test_message_output_spelling_serialization(self): + def test_provider_specification_components_security_schemes_basic_serialization(self): """ - Test serialization/deserialization for MessageOutputSpelling + Test serialization/deserialization for ProviderSpecificationComponentsSecuritySchemesBasic """ - # Construct a json representation of a MessageOutputSpelling model - message_output_spelling_model_json = {} - message_output_spelling_model_json['text'] = 'testString' - message_output_spelling_model_json['original_text'] = 'testString' - message_output_spelling_model_json['suggested_text'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation - message_output_spelling_model = MessageOutputSpelling.from_dict(message_output_spelling_model_json) - assert message_output_spelling_model != False + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation - message_output_spelling_model_dict = MessageOutputSpelling.from_dict(message_output_spelling_model_json).__dict__ - message_output_spelling_model2 = MessageOutputSpelling(**message_output_spelling_model_dict) + # Construct a json representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model_json = {} + provider_specification_components_security_schemes_basic_model_json['username'] = provider_authentication_type_and_value_model + + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_specification_components_security_schemes_basic_model = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict(provider_specification_components_security_schemes_basic_model_json) + assert provider_specification_components_security_schemes_basic_model != False + + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_specification_components_security_schemes_basic_model_dict = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict(provider_specification_components_security_schemes_basic_model_json).__dict__ + provider_specification_components_security_schemes_basic_model2 = ProviderSpecificationComponentsSecuritySchemesBasic(**provider_specification_components_security_schemes_basic_model_dict) # Verify the model instances are equivalent - assert message_output_spelling_model == message_output_spelling_model2 + assert provider_specification_components_security_schemes_basic_model == provider_specification_components_security_schemes_basic_model2 # Convert model instance back to dict and verify no loss of data - message_output_spelling_model_json2 = message_output_spelling_model.to_dict() - assert message_output_spelling_model_json2 == message_output_spelling_model_json + provider_specification_components_security_schemes_basic_model_json2 = provider_specification_components_security_schemes_basic_model.to_dict() + assert provider_specification_components_security_schemes_basic_model_json2 == provider_specification_components_security_schemes_basic_model_json -class TestModel_Pagination: +class TestModel_ProviderSpecificationServersItem: """ - Test Class for Pagination + Test Class for ProviderSpecificationServersItem """ - def test_pagination_serialization(self): + def test_provider_specification_servers_item_serialization(self): """ - Test serialization/deserialization for Pagination + Test serialization/deserialization for ProviderSpecificationServersItem """ - # Construct a json representation of a Pagination model - pagination_model_json = {} - pagination_model_json['refresh_url'] = 'testString' - pagination_model_json['next_url'] = 'testString' - pagination_model_json['total'] = 38 - pagination_model_json['matched'] = 38 - pagination_model_json['refresh_cursor'] = 'testString' - pagination_model_json['next_cursor'] = 'testString' + # Construct a json representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model_json = {} + provider_specification_servers_item_model_json['url'] = 'testString' - # Construct a model instance of Pagination by calling from_dict on the json representation - pagination_model = Pagination.from_dict(pagination_model_json) - assert pagination_model != False + # Construct a model instance of ProviderSpecificationServersItem by calling from_dict on the json representation + provider_specification_servers_item_model = ProviderSpecificationServersItem.from_dict(provider_specification_servers_item_model_json) + assert provider_specification_servers_item_model != False - # Construct a model instance of Pagination by calling from_dict on the json representation - pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ - pagination_model2 = Pagination(**pagination_model_dict) + # Construct a model instance of ProviderSpecificationServersItem by calling from_dict on the json representation + provider_specification_servers_item_model_dict = ProviderSpecificationServersItem.from_dict(provider_specification_servers_item_model_json).__dict__ + provider_specification_servers_item_model2 = ProviderSpecificationServersItem(**provider_specification_servers_item_model_dict) # Verify the model instances are equivalent - assert pagination_model == pagination_model2 + assert provider_specification_servers_item_model == provider_specification_servers_item_model2 # Convert model instance back to dict and verify no loss of data - pagination_model_json2 = pagination_model.to_dict() - assert pagination_model_json2 == pagination_model_json + provider_specification_servers_item_model_json2 = provider_specification_servers_item_model.to_dict() + assert provider_specification_servers_item_model_json2 == provider_specification_servers_item_model_json class TestModel_Release: @@ -7244,7 +10074,7 @@ def test_search_result_highlight_serialization(self): expected_dict = {'foo': ['testString']} search_result_highlight_model.set_properties(expected_dict) actual_dict = search_result_highlight_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_SearchResultMetadata: @@ -7315,11 +10145,52 @@ def test_search_settings_serialization(self): search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' + search_settings_elastic_search_model = {} # SearchSettingsElasticSearch + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + # Construct a json representation of a SearchSettings model search_settings_model_json = {} search_settings_model_json['discovery'] = search_settings_discovery_model search_settings_model_json['messages'] = search_settings_messages_model search_settings_model_json['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model_json['elastic_search'] = search_settings_elastic_search_model + search_settings_model_json['conversational_search'] = search_settings_conversational_search_model + search_settings_model_json['server_side_search'] = search_settings_server_side_search_model + search_settings_model_json['client_side_search'] = search_settings_client_side_search_model # Construct a model instance of SearchSettings by calling from_dict on the json representation search_settings_model = SearchSettings.from_dict(search_settings_model_json) @@ -7330,11 +10201,142 @@ def test_search_settings_serialization(self): search_settings_model2 = SearchSettings(**search_settings_model_dict) # Verify the model instances are equivalent - assert search_settings_model == search_settings_model2 + assert search_settings_model == search_settings_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_model_json2 = search_settings_model.to_dict() + assert search_settings_model_json2 == search_settings_model_json + + +class TestModel_SearchSettingsClientSideSearch: + """ + Test Class for SearchSettingsClientSideSearch + """ + + def test_search_settings_client_side_search_serialization(self): + """ + Test serialization/deserialization for SearchSettingsClientSideSearch + """ + + # Construct a json representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model_json = {} + search_settings_client_side_search_model_json['filter'] = 'testString' + search_settings_client_side_search_model_json['metadata'] = {'anyKey': 'anyValue'} + + # Construct a model instance of SearchSettingsClientSideSearch by calling from_dict on the json representation + search_settings_client_side_search_model = SearchSettingsClientSideSearch.from_dict(search_settings_client_side_search_model_json) + assert search_settings_client_side_search_model != False + + # Construct a model instance of SearchSettingsClientSideSearch by calling from_dict on the json representation + search_settings_client_side_search_model_dict = SearchSettingsClientSideSearch.from_dict(search_settings_client_side_search_model_json).__dict__ + search_settings_client_side_search_model2 = SearchSettingsClientSideSearch(**search_settings_client_side_search_model_dict) + + # Verify the model instances are equivalent + assert search_settings_client_side_search_model == search_settings_client_side_search_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_client_side_search_model_json2 = search_settings_client_side_search_model.to_dict() + assert search_settings_client_side_search_model_json2 == search_settings_client_side_search_model_json + + +class TestModel_SearchSettingsConversationalSearch: + """ + Test Class for SearchSettingsConversationalSearch + """ + + def test_search_settings_conversational_search_serialization(self): + """ + Test serialization/deserialization for SearchSettingsConversationalSearch + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a json representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model_json = {} + search_settings_conversational_search_model_json['enabled'] = True + search_settings_conversational_search_model_json['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model_json['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a model instance of SearchSettingsConversationalSearch by calling from_dict on the json representation + search_settings_conversational_search_model = SearchSettingsConversationalSearch.from_dict(search_settings_conversational_search_model_json) + assert search_settings_conversational_search_model != False + + # Construct a model instance of SearchSettingsConversationalSearch by calling from_dict on the json representation + search_settings_conversational_search_model_dict = SearchSettingsConversationalSearch.from_dict(search_settings_conversational_search_model_json).__dict__ + search_settings_conversational_search_model2 = SearchSettingsConversationalSearch(**search_settings_conversational_search_model_dict) + + # Verify the model instances are equivalent + assert search_settings_conversational_search_model == search_settings_conversational_search_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_conversational_search_model_json2 = search_settings_conversational_search_model.to_dict() + assert search_settings_conversational_search_model_json2 == search_settings_conversational_search_model_json + + +class TestModel_SearchSettingsConversationalSearchResponseLength: + """ + Test Class for SearchSettingsConversationalSearchResponseLength + """ + + def test_search_settings_conversational_search_response_length_serialization(self): + """ + Test serialization/deserialization for SearchSettingsConversationalSearchResponseLength + """ + + # Construct a json representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model_json = {} + search_settings_conversational_search_response_length_model_json['option'] = 'moderate' + + # Construct a model instance of SearchSettingsConversationalSearchResponseLength by calling from_dict on the json representation + search_settings_conversational_search_response_length_model = SearchSettingsConversationalSearchResponseLength.from_dict(search_settings_conversational_search_response_length_model_json) + assert search_settings_conversational_search_response_length_model != False + + # Construct a model instance of SearchSettingsConversationalSearchResponseLength by calling from_dict on the json representation + search_settings_conversational_search_response_length_model_dict = SearchSettingsConversationalSearchResponseLength.from_dict(search_settings_conversational_search_response_length_model_json).__dict__ + search_settings_conversational_search_response_length_model2 = SearchSettingsConversationalSearchResponseLength(**search_settings_conversational_search_response_length_model_dict) + + # Verify the model instances are equivalent + assert search_settings_conversational_search_response_length_model == search_settings_conversational_search_response_length_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_conversational_search_response_length_model_json2 = search_settings_conversational_search_response_length_model.to_dict() + assert search_settings_conversational_search_response_length_model_json2 == search_settings_conversational_search_response_length_model_json + + +class TestModel_SearchSettingsConversationalSearchSearchConfidence: + """ + Test Class for SearchSettingsConversationalSearchSearchConfidence + """ + + def test_search_settings_conversational_search_search_confidence_serialization(self): + """ + Test serialization/deserialization for SearchSettingsConversationalSearchSearchConfidence + """ + + # Construct a json representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model_json = {} + search_settings_conversational_search_search_confidence_model_json['threshold'] = 'less_often' + + # Construct a model instance of SearchSettingsConversationalSearchSearchConfidence by calling from_dict on the json representation + search_settings_conversational_search_search_confidence_model = SearchSettingsConversationalSearchSearchConfidence.from_dict(search_settings_conversational_search_search_confidence_model_json) + assert search_settings_conversational_search_search_confidence_model != False + + # Construct a model instance of SearchSettingsConversationalSearchSearchConfidence by calling from_dict on the json representation + search_settings_conversational_search_search_confidence_model_dict = SearchSettingsConversationalSearchSearchConfidence.from_dict(search_settings_conversational_search_search_confidence_model_json).__dict__ + search_settings_conversational_search_search_confidence_model2 = SearchSettingsConversationalSearchSearchConfidence(**search_settings_conversational_search_search_confidence_model_dict) + + # Verify the model instances are equivalent + assert search_settings_conversational_search_search_confidence_model == search_settings_conversational_search_search_confidence_model2 # Convert model instance back to dict and verify no loss of data - search_settings_model_json2 = search_settings_model.to_dict() - assert search_settings_model_json2 == search_settings_model_json + search_settings_conversational_search_search_confidence_model_json2 = search_settings_conversational_search_search_confidence_model.to_dict() + assert search_settings_conversational_search_search_confidence_model_json2 == search_settings_conversational_search_search_confidence_model_json class TestModel_SearchSettingsDiscovery: @@ -7412,6 +10414,44 @@ def test_search_settings_discovery_authentication_serialization(self): assert search_settings_discovery_authentication_model_json2 == search_settings_discovery_authentication_model_json +class TestModel_SearchSettingsElasticSearch: + """ + Test Class for SearchSettingsElasticSearch + """ + + def test_search_settings_elastic_search_serialization(self): + """ + Test serialization/deserialization for SearchSettingsElasticSearch + """ + + # Construct a json representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model_json = {} + search_settings_elastic_search_model_json['url'] = 'testString' + search_settings_elastic_search_model_json['port'] = 'testString' + search_settings_elastic_search_model_json['username'] = 'testString' + search_settings_elastic_search_model_json['password'] = 'testString' + search_settings_elastic_search_model_json['index'] = 'testString' + search_settings_elastic_search_model_json['filter'] = ['testString'] + search_settings_elastic_search_model_json['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model_json['managed_index'] = 'testString' + search_settings_elastic_search_model_json['apikey'] = 'testString' + + # Construct a model instance of SearchSettingsElasticSearch by calling from_dict on the json representation + search_settings_elastic_search_model = SearchSettingsElasticSearch.from_dict(search_settings_elastic_search_model_json) + assert search_settings_elastic_search_model != False + + # Construct a model instance of SearchSettingsElasticSearch by calling from_dict on the json representation + search_settings_elastic_search_model_dict = SearchSettingsElasticSearch.from_dict(search_settings_elastic_search_model_json).__dict__ + search_settings_elastic_search_model2 = SearchSettingsElasticSearch(**search_settings_elastic_search_model_dict) + + # Verify the model instances are equivalent + assert search_settings_elastic_search_model == search_settings_elastic_search_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_elastic_search_model_json2 = search_settings_elastic_search_model.to_dict() + assert search_settings_elastic_search_model_json2 == search_settings_elastic_search_model_json + + class TestModel_SearchSettingsMessages: """ Test Class for SearchSettingsMessages @@ -7476,6 +10516,44 @@ def test_search_settings_schema_mapping_serialization(self): assert search_settings_schema_mapping_model_json2 == search_settings_schema_mapping_model_json +class TestModel_SearchSettingsServerSideSearch: + """ + Test Class for SearchSettingsServerSideSearch + """ + + def test_search_settings_server_side_search_serialization(self): + """ + Test serialization/deserialization for SearchSettingsServerSideSearch + """ + + # Construct a json representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model_json = {} + search_settings_server_side_search_model_json['url'] = 'testString' + search_settings_server_side_search_model_json['port'] = 'testString' + search_settings_server_side_search_model_json['username'] = 'testString' + search_settings_server_side_search_model_json['password'] = 'testString' + search_settings_server_side_search_model_json['filter'] = 'testString' + search_settings_server_side_search_model_json['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model_json['apikey'] = 'testString' + search_settings_server_side_search_model_json['no_auth'] = True + search_settings_server_side_search_model_json['auth_type'] = 'basic' + + # Construct a model instance of SearchSettingsServerSideSearch by calling from_dict on the json representation + search_settings_server_side_search_model = SearchSettingsServerSideSearch.from_dict(search_settings_server_side_search_model_json) + assert search_settings_server_side_search_model != False + + # Construct a model instance of SearchSettingsServerSideSearch by calling from_dict on the json representation + search_settings_server_side_search_model_dict = SearchSettingsServerSideSearch.from_dict(search_settings_server_side_search_model_json).__dict__ + search_settings_server_side_search_model2 = SearchSettingsServerSideSearch(**search_settings_server_side_search_model_dict) + + # Verify the model instances are equivalent + assert search_settings_server_side_search_model == search_settings_server_side_search_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_server_side_search_model_json2 = search_settings_server_side_search_model.to_dict() + assert search_settings_server_side_search_model_json2 == search_settings_server_side_search_model_json + + class TestModel_SearchSkillWarning: """ Test Class for SearchSkillWarning @@ -7575,10 +10653,51 @@ def test_skill_serialization(self): search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' + search_settings_elastic_search_model = {} # SearchSettingsElasticSearch + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_model = {} # SearchSettings search_settings_model['discovery'] = search_settings_discovery_model search_settings_model['messages'] = search_settings_messages_model search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model # Construct a json representation of a Skill model skill_model_json = {} @@ -7643,10 +10762,51 @@ def test_skill_import_serialization(self): search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' + search_settings_elastic_search_model = {} # SearchSettingsElasticSearch + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_model = {} # SearchSettings search_settings_model['discovery'] = search_settings_discovery_model search_settings_model['messages'] = search_settings_messages_model search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model # Construct a json representation of a SkillImport model skill_import_model_json = {} @@ -7740,10 +10900,51 @@ def test_skills_export_serialization(self): search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' + search_settings_elastic_search_model = {} # SearchSettingsElasticSearch + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_model = {} # SearchSettings search_settings_model['discovery'] = search_settings_discovery_model search_settings_model['messages'] = search_settings_messages_model search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model skill_model = {} # Skill skill_model['name'] = 'testString' @@ -8658,11 +11859,28 @@ def test_turn_event_callout_callout_serialization(self): Test serialization/deserialization for TurnEventCalloutCallout """ + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_callout_callout_request_model = {} # TurnEventCalloutCalloutRequest + turn_event_callout_callout_request_model['method'] = 'get' + turn_event_callout_callout_request_model['url'] = 'testString' + turn_event_callout_callout_request_model['path'] = 'testString' + turn_event_callout_callout_request_model['query_parameters'] = 'testString' + turn_event_callout_callout_request_model['headers'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_request_model['body'] = {'anyKey': 'anyValue'} + + turn_event_callout_callout_response_model = {} # TurnEventCalloutCalloutResponse + turn_event_callout_callout_response_model['body'] = 'testString' + turn_event_callout_callout_response_model['status_code'] = 38 + turn_event_callout_callout_response_model['last_event'] = {'anyKey': 'anyValue'} + # Construct a json representation of a TurnEventCalloutCallout model turn_event_callout_callout_model_json = {} turn_event_callout_callout_model_json['type'] = 'integration_interaction' turn_event_callout_callout_model_json['internal'] = {'anyKey': 'anyValue'} turn_event_callout_callout_model_json['result_variable'] = 'testString' + turn_event_callout_callout_model_json['request'] = turn_event_callout_callout_request_model + turn_event_callout_callout_model_json['response'] = turn_event_callout_callout_response_model # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation turn_event_callout_callout_model = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json) @@ -8680,6 +11898,73 @@ def test_turn_event_callout_callout_serialization(self): assert turn_event_callout_callout_model_json2 == turn_event_callout_callout_model_json +class TestModel_TurnEventCalloutCalloutRequest: + """ + Test Class for TurnEventCalloutCalloutRequest + """ + + def test_turn_event_callout_callout_request_serialization(self): + """ + Test serialization/deserialization for TurnEventCalloutCalloutRequest + """ + + # Construct a json representation of a TurnEventCalloutCalloutRequest model + turn_event_callout_callout_request_model_json = {} + turn_event_callout_callout_request_model_json['method'] = 'get' + turn_event_callout_callout_request_model_json['url'] = 'testString' + turn_event_callout_callout_request_model_json['path'] = 'testString' + turn_event_callout_callout_request_model_json['query_parameters'] = 'testString' + turn_event_callout_callout_request_model_json['headers'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_request_model_json['body'] = {'anyKey': 'anyValue'} + + # Construct a model instance of TurnEventCalloutCalloutRequest by calling from_dict on the json representation + turn_event_callout_callout_request_model = TurnEventCalloutCalloutRequest.from_dict(turn_event_callout_callout_request_model_json) + assert turn_event_callout_callout_request_model != False + + # Construct a model instance of TurnEventCalloutCalloutRequest by calling from_dict on the json representation + turn_event_callout_callout_request_model_dict = TurnEventCalloutCalloutRequest.from_dict(turn_event_callout_callout_request_model_json).__dict__ + turn_event_callout_callout_request_model2 = TurnEventCalloutCalloutRequest(**turn_event_callout_callout_request_model_dict) + + # Verify the model instances are equivalent + assert turn_event_callout_callout_request_model == turn_event_callout_callout_request_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_callout_callout_request_model_json2 = turn_event_callout_callout_request_model.to_dict() + assert turn_event_callout_callout_request_model_json2 == turn_event_callout_callout_request_model_json + + +class TestModel_TurnEventCalloutCalloutResponse: + """ + Test Class for TurnEventCalloutCalloutResponse + """ + + def test_turn_event_callout_callout_response_serialization(self): + """ + Test serialization/deserialization for TurnEventCalloutCalloutResponse + """ + + # Construct a json representation of a TurnEventCalloutCalloutResponse model + turn_event_callout_callout_response_model_json = {} + turn_event_callout_callout_response_model_json['body'] = 'testString' + turn_event_callout_callout_response_model_json['status_code'] = 38 + turn_event_callout_callout_response_model_json['last_event'] = {'anyKey': 'anyValue'} + + # Construct a model instance of TurnEventCalloutCalloutResponse by calling from_dict on the json representation + turn_event_callout_callout_response_model = TurnEventCalloutCalloutResponse.from_dict(turn_event_callout_callout_response_model_json) + assert turn_event_callout_callout_response_model != False + + # Construct a model instance of TurnEventCalloutCalloutResponse by calling from_dict on the json representation + turn_event_callout_callout_response_model_dict = TurnEventCalloutCalloutResponse.from_dict(turn_event_callout_callout_response_model_json).__dict__ + turn_event_callout_callout_response_model2 = TurnEventCalloutCalloutResponse(**turn_event_callout_callout_response_model_dict) + + # Verify the model instances are equivalent + assert turn_event_callout_callout_response_model == turn_event_callout_callout_response_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_callout_callout_response_model_json2 = turn_event_callout_callout_response_model.to_dict() + assert turn_event_callout_callout_response_model_json2 == turn_event_callout_callout_response_model_json + + class TestModel_TurnEventCalloutError: """ Test Class for TurnEventCalloutError @@ -8773,6 +12058,101 @@ def test_turn_event_search_error_serialization(self): assert turn_event_search_error_model_json2 == turn_event_search_error_model_json +class TestModel_UpdateEnvironmentOrchestration: + """ + Test Class for UpdateEnvironmentOrchestration + """ + + def test_update_environment_orchestration_serialization(self): + """ + Test serialization/deserialization for UpdateEnvironmentOrchestration + """ + + # Construct a json representation of a UpdateEnvironmentOrchestration model + update_environment_orchestration_model_json = {} + update_environment_orchestration_model_json['search_skill_fallback'] = True + + # Construct a model instance of UpdateEnvironmentOrchestration by calling from_dict on the json representation + update_environment_orchestration_model = UpdateEnvironmentOrchestration.from_dict(update_environment_orchestration_model_json) + assert update_environment_orchestration_model != False + + # Construct a model instance of UpdateEnvironmentOrchestration by calling from_dict on the json representation + update_environment_orchestration_model_dict = UpdateEnvironmentOrchestration.from_dict(update_environment_orchestration_model_json).__dict__ + update_environment_orchestration_model2 = UpdateEnvironmentOrchestration(**update_environment_orchestration_model_dict) + + # Verify the model instances are equivalent + assert update_environment_orchestration_model == update_environment_orchestration_model2 + + # Convert model instance back to dict and verify no loss of data + update_environment_orchestration_model_json2 = update_environment_orchestration_model.to_dict() + assert update_environment_orchestration_model_json2 == update_environment_orchestration_model_json + + +class TestModel_UpdateEnvironmentReleaseReference: + """ + Test Class for UpdateEnvironmentReleaseReference + """ + + def test_update_environment_release_reference_serialization(self): + """ + Test serialization/deserialization for UpdateEnvironmentReleaseReference + """ + + # Construct a json representation of a UpdateEnvironmentReleaseReference model + update_environment_release_reference_model_json = {} + update_environment_release_reference_model_json['release'] = 'testString' + + # Construct a model instance of UpdateEnvironmentReleaseReference by calling from_dict on the json representation + update_environment_release_reference_model = UpdateEnvironmentReleaseReference.from_dict(update_environment_release_reference_model_json) + assert update_environment_release_reference_model != False + + # Construct a model instance of UpdateEnvironmentReleaseReference by calling from_dict on the json representation + update_environment_release_reference_model_dict = UpdateEnvironmentReleaseReference.from_dict(update_environment_release_reference_model_json).__dict__ + update_environment_release_reference_model2 = UpdateEnvironmentReleaseReference(**update_environment_release_reference_model_dict) + + # Verify the model instances are equivalent + assert update_environment_release_reference_model == update_environment_release_reference_model2 + + # Convert model instance back to dict and verify no loss of data + update_environment_release_reference_model_json2 = update_environment_release_reference_model.to_dict() + assert update_environment_release_reference_model_json2 == update_environment_release_reference_model_json + + +class TestModel_CompleteItem: + """ + Test Class for CompleteItem + """ + + def test_complete_item_serialization(self): + """ + Test serialization/deserialization for CompleteItem + """ + + # Construct dict forms of any model objects needed in order to build this model. + + metadata_model = {} # Metadata + metadata_model['id'] = 38 + + # Construct a json representation of a CompleteItem model + complete_item_model_json = {} + complete_item_model_json['streaming_metadata'] = metadata_model + + # Construct a model instance of CompleteItem by calling from_dict on the json representation + complete_item_model = CompleteItem.from_dict(complete_item_model_json) + assert complete_item_model != False + + # Construct a model instance of CompleteItem by calling from_dict on the json representation + complete_item_model_dict = CompleteItem.from_dict(complete_item_model_json).__dict__ + complete_item_model2 = CompleteItem(**complete_item_model_dict) + + # Verify the model instances are equivalent + assert complete_item_model == complete_item_model2 + + # Convert model instance back to dict and verify no loss of data + complete_item_model_json2 = complete_item_model.to_dict() + assert complete_item_model_json2 == complete_item_model_json + + class TestModel_LogMessageSourceAction: """ Test Class for LogMessageSourceAction @@ -9004,10 +12384,25 @@ def test_message_output_debug_turn_event_turn_event_callout_serialization(self): turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' + turn_event_callout_callout_request_model = {} # TurnEventCalloutCalloutRequest + turn_event_callout_callout_request_model['method'] = 'get' + turn_event_callout_callout_request_model['url'] = 'testString' + turn_event_callout_callout_request_model['path'] = 'testString' + turn_event_callout_callout_request_model['query_parameters'] = 'testString' + turn_event_callout_callout_request_model['headers'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_request_model['body'] = {'anyKey': 'anyValue'} + + turn_event_callout_callout_response_model = {} # TurnEventCalloutCalloutResponse + turn_event_callout_callout_response_model['body'] = 'testString' + turn_event_callout_callout_response_model['status_code'] = 38 + turn_event_callout_callout_response_model['last_event'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_model = {} # TurnEventCalloutCallout turn_event_callout_callout_model['type'] = 'integration_interaction' turn_event_callout_callout_model['internal'] = {'anyKey': 'anyValue'} turn_event_callout_callout_model['result_variable'] = 'testString' + turn_event_callout_callout_model['request'] = turn_event_callout_callout_request_model + turn_event_callout_callout_model['response'] = turn_event_callout_callout_response_model turn_event_callout_error_model = {} # TurnEventCalloutError turn_event_callout_error_model['message'] = 'testString' @@ -9242,6 +12637,339 @@ def test_message_output_debug_turn_event_turn_event_step_visited_serialization(s assert message_output_debug_turn_event_turn_event_step_visited_model_json2 == message_output_debug_turn_event_turn_event_step_visited_model_json +class TestModel_ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode: + """ + Test Class for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode + """ + + def test_provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_serialization(self): + """ + Test serialization/deserialization for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode + """ + + # Construct a json representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode model + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json = {} + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['token_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['content_type'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['authorization_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['redirect_uri'] = 'testString' + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json) + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model != False + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_dict = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json).__dict__ + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model2 = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode(**provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_dict) + + # Verify the model instances are equivalent + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model2 + + # Convert model instance back to dict and verify no loss of data + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json2 = provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model.to_dict() + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json2 == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json + + +class TestModel_ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials: + """ + Test Class for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials + """ + + def test_provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_serialization(self): + """ + Test serialization/deserialization for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials + """ + + # Construct a json representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials model + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json = {} + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json['token_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json['content_type'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json['header_prefix'] = 'testString' + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json) + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model != False + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_dict = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json).__dict__ + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model2 = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials(**provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_dict) + + # Verify the model instances are equivalent + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model2 + + # Convert model instance back to dict and verify no loss of data + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json2 = provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model.to_dict() + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json2 == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json + + +class TestModel_ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password: + """ + Test Class for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + """ + + def test_provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_serialization(self): + """ + Test serialization/deserialization for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + """ + + # Construct dict forms of any model objects needed in order to build this model. + + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a json representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json = {} + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['token_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['content_type'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json) + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model != False + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_dict = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json).__dict__ + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model2 = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password(**provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_dict) + + # Verify the model instances are equivalent + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model2 + + # Convert model instance back to dict and verify no loss of data + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json2 = provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model.to_dict() + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json2 == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json + + +class TestModel_ProviderPrivateAuthenticationBasicFlow: + """ + Test Class for ProviderPrivateAuthenticationBasicFlow + """ + + def test_provider_private_authentication_basic_flow_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationBasicFlow + """ + + # Construct dict forms of any model objects needed in order to build this model. + + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a json representation of a ProviderPrivateAuthenticationBasicFlow model + provider_private_authentication_basic_flow_model_json = {} + provider_private_authentication_basic_flow_model_json['password'] = provider_authentication_type_and_value_model + + # Construct a model instance of ProviderPrivateAuthenticationBasicFlow by calling from_dict on the json representation + provider_private_authentication_basic_flow_model = ProviderPrivateAuthenticationBasicFlow.from_dict(provider_private_authentication_basic_flow_model_json) + assert provider_private_authentication_basic_flow_model != False + + # Construct a model instance of ProviderPrivateAuthenticationBasicFlow by calling from_dict on the json representation + provider_private_authentication_basic_flow_model_dict = ProviderPrivateAuthenticationBasicFlow.from_dict(provider_private_authentication_basic_flow_model_json).__dict__ + provider_private_authentication_basic_flow_model2 = ProviderPrivateAuthenticationBasicFlow(**provider_private_authentication_basic_flow_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_basic_flow_model == provider_private_authentication_basic_flow_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_basic_flow_model_json2 = provider_private_authentication_basic_flow_model.to_dict() + assert provider_private_authentication_basic_flow_model_json2 == provider_private_authentication_basic_flow_model_json + + +class TestModel_ProviderPrivateAuthenticationBearerFlow: + """ + Test Class for ProviderPrivateAuthenticationBearerFlow + """ + + def test_provider_private_authentication_bearer_flow_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationBearerFlow + """ + + # Construct dict forms of any model objects needed in order to build this model. + + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a json representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_bearer_flow_model_json = {} + provider_private_authentication_bearer_flow_model_json['token'] = provider_authentication_type_and_value_model + + # Construct a model instance of ProviderPrivateAuthenticationBearerFlow by calling from_dict on the json representation + provider_private_authentication_bearer_flow_model = ProviderPrivateAuthenticationBearerFlow.from_dict(provider_private_authentication_bearer_flow_model_json) + assert provider_private_authentication_bearer_flow_model != False + + # Construct a model instance of ProviderPrivateAuthenticationBearerFlow by calling from_dict on the json representation + provider_private_authentication_bearer_flow_model_dict = ProviderPrivateAuthenticationBearerFlow.from_dict(provider_private_authentication_bearer_flow_model_json).__dict__ + provider_private_authentication_bearer_flow_model2 = ProviderPrivateAuthenticationBearerFlow(**provider_private_authentication_bearer_flow_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_bearer_flow_model == provider_private_authentication_bearer_flow_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_bearer_flow_model_json2 = provider_private_authentication_bearer_flow_model.to_dict() + assert provider_private_authentication_bearer_flow_model_json2 == provider_private_authentication_bearer_flow_model_json + + +class TestModel_ProviderPrivateAuthenticationOAuth2Flow: + """ + Test Class for ProviderPrivateAuthenticationOAuth2Flow + """ + + def test_provider_private_authentication_o_auth2_flow_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2Flow + """ + + # Construct dict forms of any model objects needed in order to build this model. + + provider_private_authentication_o_auth2_password_password_model = {} # ProviderPrivateAuthenticationOAuth2PasswordPassword + provider_private_authentication_o_auth2_password_password_model['type'] = 'value' + provider_private_authentication_o_auth2_password_password_model['value'] = 'testString' + + provider_private_authentication_o_auth2_flow_flows_model = {} # ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password + provider_private_authentication_o_auth2_flow_flows_model['client_id'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_model['client_secret'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_model['access_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_model['refresh_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_model['password'] = provider_private_authentication_o_auth2_password_password_model + + # Construct a json representation of a ProviderPrivateAuthenticationOAuth2Flow model + provider_private_authentication_o_auth2_flow_model_json = {} + provider_private_authentication_o_auth2_flow_model_json['flows'] = provider_private_authentication_o_auth2_flow_flows_model + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2Flow by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_model = ProviderPrivateAuthenticationOAuth2Flow.from_dict(provider_private_authentication_o_auth2_flow_model_json) + assert provider_private_authentication_o_auth2_flow_model != False + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2Flow by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_model_dict = ProviderPrivateAuthenticationOAuth2Flow.from_dict(provider_private_authentication_o_auth2_flow_model_json).__dict__ + provider_private_authentication_o_auth2_flow_model2 = ProviderPrivateAuthenticationOAuth2Flow(**provider_private_authentication_o_auth2_flow_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_o_auth2_flow_model == provider_private_authentication_o_auth2_flow_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_o_auth2_flow_model_json2 = provider_private_authentication_o_auth2_flow_model.to_dict() + assert provider_private_authentication_o_auth2_flow_model_json2 == provider_private_authentication_o_auth2_flow_model_json + + +class TestModel_ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode: + """ + Test Class for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode + """ + + def test_provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode + """ + + # Construct a json representation of a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode model + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json = {} + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json['client_id'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json['client_secret'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json['access_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json['refresh_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json['authorization_code'] = 'testString' + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json) + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model != False + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_dict = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json).__dict__ + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model2 = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode(**provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json2 = provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model.to_dict() + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json2 == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json + + +class TestModel_ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials: + """ + Test Class for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials + """ + + def test_provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials + """ + + # Construct a json representation of a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials model + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json = {} + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json['client_id'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json['client_secret'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json['access_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json['refresh_token'] = 'testString' + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json) + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model != False + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_dict = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json).__dict__ + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model2 = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials(**provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json2 = provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model.to_dict() + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json2 == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json + + +class TestModel_ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password: + """ + Test Class for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password + """ + + def test_provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password + """ + + # Construct dict forms of any model objects needed in order to build this model. + + provider_private_authentication_o_auth2_password_password_model = {} # ProviderPrivateAuthenticationOAuth2PasswordPassword + provider_private_authentication_o_auth2_password_password_model['type'] = 'value' + provider_private_authentication_o_auth2_password_password_model['value'] = 'testString' + + # Construct a json representation of a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password model + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json = {} + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json['client_id'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json['client_secret'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json['access_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json['refresh_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json['password'] = provider_private_authentication_o_auth2_password_password_model + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json) + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model != False + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_dict = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json).__dict__ + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model2 = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password(**provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json2 = provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model.to_dict() + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json2 == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json + + class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeAudio From af0ef69170d736974f392ac69a46c4d055ff271c Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 22 Nov 2024 12:29:29 -0500 Subject: [PATCH 10/11] feat(common): add parse_sse_stream_data function This function parses the raw buffer recieved from sse requests and yields a parsed dictionary --- ibm_watson/common.py | 23 +++++++++- test/integration/test_assistant_v2.py | 65 +++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 test/integration/test_assistant_v2.py diff --git a/ibm_watson/common.py b/ibm_watson/common.py index 81ecc7ec..a1595d61 100644 --- a/ibm_watson/common.py +++ b/ibm_watson/common.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2019 IBM All Rights Reserved. +# Copyright 2019, 2024 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,7 +15,9 @@ # limitations under the License. import platform +import json from .version import __version__ +from typing import Iterator SDK_ANALYTICS_HEADER = 'X-IBMCloud-SDK-Analytics' USER_AGENT_HEADER = 'User-Agent' @@ -48,3 +50,22 @@ def get_sdk_headers(service_name, service_version, operation_id): operation_id) headers[USER_AGENT_HEADER] = get_user_agent() return headers + + +def parse_sse_stream_data(response) -> Iterator[dict]: + event_message = None # Can be used in the future to return the event message to the user + data_json = None + + for chunk in response.iter_lines(): + decoded_chunk = chunk.decode("utf-8") + + if decoded_chunk.find("event", 0, len("event")) == 0: + event_message = decoded_chunk[len("event") + 2:] + elif decoded_chunk.find("data", 0, len("data")) == 0: + data_json_str = decoded_chunk[len("data") + 2:] + data_json = json.loads(data_json_str) + + if event_message and data_json is not None: + yield data_json + event_message = None + data_json = None diff --git a/test/integration/test_assistant_v2.py b/test/integration/test_assistant_v2.py new file mode 100644 index 00000000..db17bcae --- /dev/null +++ b/test/integration/test_assistant_v2.py @@ -0,0 +1,65 @@ +# coding: utf-8 + +# Copyright 2019, 2024 IBM All Rights Reserved. +# +# 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 unittest import TestCase +import ibm_watson +from ibm_watson.assistant_v2 import MessageInput +from ibm_watson.common import parse_sse_stream_data +import pytest +import json +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator + +class TestAssistantV2(TestCase): + + def setUp(self): + + with open('./auth.json') as f: + data = json.load(f) + assistant_auth = data.get("assistantv2") + self.assistant_id = assistant_auth.get("assistantId") + self.environment_id = assistant_auth.get("environmentId") + + self.authenticator = IAMAuthenticator(apikey=assistant_auth.get("apikey")) + self.assistant = ibm_watson.AssistantV2(version='2024-08-25', authenticator=self.authenticator) + self.assistant.set_service_url(assistant_auth.get("serviceUrl")) + self.assistant.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) + + def test_list_assistants(self): + response = self.assistant.list_assistants().get_result() + assert response is not None + + def test_message_stream_stateless(self): + input = MessageInput(message_type="text", text="can you list the steps to create a custom extension?") + user_id = "Angelo" + + response = self.assistant.message_stream_stateless(self.assistant_id, self.environment_id, input=input, user_id=user_id).get_result() + + for data in parse_sse_stream_data(response): + # One of these items must exist + # assert "partial_item" in data_json or "complete_item" in data_json or "final_item" in data_json + + if "partial_item" in data: + assert data["partial_item"]["text"] is not None + elif "complete_item" in data: + assert data["complete_item"]["text"] is not None + elif "final_response" in data: + assert data["final_response"] is not None + else: + pytest.fail("Should be impossible to get here") + From b04f6419a931e024cff5a0adec7de2adf313c0c3 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 4 Dec 2024 12:37:52 -0600 Subject: [PATCH 11/11] build(actions): update tested python versions --- .github/workflows/build-test.yml | 37 ++++++++------------------------ 1 file changed, 9 insertions(+), 28 deletions(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 4849b2f4..c5175d31 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -21,11 +21,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ['3.9', '3.10', '3.11'] - os: [ubuntu-latest, windows-latest] - exclude: - - os: windows-latest - python-version: '3.9' + python-version: ['3.11', '3.12', '3.13'] + os: [ubuntu-latest] steps: - uses: actions/checkout@v2 @@ -39,39 +36,23 @@ jobs: pip3 install -r requirements.txt pip3 install -r requirements-dev.txt pip3 install --editable . - - name: Install dependencies (windows) - if: matrix.os == 'windows-latest' - run: | - pip3 install -r requirements.txt --use-deprecated=legacy-resolver - pip3 install -r requirements-dev.txt --use-deprecated=legacy-resolver - pip3 install --editable . --use-deprecated=legacy-resolver - - name: Execute Python 3.9 unit tests - if: matrix.python-version == '3.9' + - name: Execute Python 3.11 unit tests + if: matrix.python-version == '3.11' run: | pip3 install -U python-dotenv py.test test/unit - - name: Execute Python 3.10 unit tests (windows) - if: matrix.python-version == '3.10' && matrix.os == 'windows-latest' - run: | - pip3 install -U python-dotenv - py.test test/unit --reruns 3 - - name: Execute Python 3.10 unit tests (ubuntu) - if: matrix.python-version == '3.10' && matrix.os == 'ubuntu-latest' + - name: Execute Python 3.12 unit tests (ubuntu) + if: matrix.python-version == '3.12' && matrix.os == 'ubuntu-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 --cov=ibm_watson - - name: Execute Python 3.11 unit tests (windows) - if: matrix.python-version == '3.11' && matrix.os == 'windows-latest' - run: | - pip3 install -U python-dotenv - py.test test/unit --reruns 3 - - name: Execute Python 3.11 unit tests (ubuntu) - if: matrix.python-version == '3.11' && matrix.os == 'ubuntu-latest' + - name: Execute Python 3.13 unit tests (ubuntu) + if: matrix.python-version == '3.13' && matrix.os == 'ubuntu-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 - name: Upload coverage to Codecov - if: matrix.python-version == '3.10' && matrix.os == 'ubuntu-latest' + if: matrix.python-version == '3.12' && matrix.os == 'ubuntu-latest' uses: codecov/codecov-action@v1 with: name: py${{ matrix.python-version }}-${{ matrix.os }}