def test_check_last_order(self): from pizza_order.pizza_helpers import check_last_order from shared.client import get_client intent_request = {"requestAttributes": {"email": "*****@*****.**"}} dynamo_client = get_client("dynamodb") stubber = Stubber(dynamo_client) dynamo_expected_params = { "TableName": "test_table", "IndexName": "test_index", "KeyConditionExpression": "customerId = :email", "ExpressionAttributeValues": { ":email": { "S": "*****@*****.**" } }, "ScanIndexForward": False, } # last order exists dynamo_response = { "Items": [{ "customerId": { "S": "testValue" }, "testKey": { "S": "testValue" } }] } stubber.add_response("query", dynamo_response, dynamo_expected_params) with stubber: has_order, response = check_last_order(intent_request) self.assertTrue(has_order) self.assertEqual(response, {"testKey": {"S": "testValue"}}) stubber.assert_no_pending_responses() # last order doesn't exist dynamo_response = {"Items": []} stubber.add_response("query", dynamo_response, dynamo_expected_params) with stubber: has_order, response = check_last_order(intent_request) self.assertFalse(has_order) self.assertEqual(response, None) stubber.assert_no_pending_responses()
# and limitations under the License. # ###################################################################################################################### import os from shared.client import get_client from shared.logger import get_logger from book_appointment.appointment_helpers import ( clarification_prompt, slot_types, utterances, confirmation_prompt, decline_reponse, closing_response, slot_message, ) client = get_client("lexv2-models") logger = get_logger(__name__) def create_intent(bot_id, locale_id): intent_response = client.create_intent( intentName="MakeAppointment", botId=bot_id, botVersion="DRAFT", localeId=locale_id, ) return intent_response def create_appointment_slot_type(bot_language, bot_id, locale_id): slot_type_response = client.create_slot_type(
def test_custom_resource(self): client = get_client("lexv2-models") stubber = Stubber(client) # Create Appointment Bot create_bot_expected_params = { "botName": mock_env_variables['botName'], "description": "Created by Serverless Bot Framework", "roleArn": mock_env_variables['botRole'], "dataPrivacy": { "childDirected": False }, "idleSessionTTLInSeconds": 300, "botTags": { "createdby": "serverless bot framework" } } create_bot_response = { 'botId': 'testid1234', 'botName': 'testbot', 'description': 'Created by Serverless Bot Framework', 'roleArn': 'arn:aws:iam::123456789012:role/testrole', 'dataPrivacy': { 'childDirected': False }, 'idleSessionTTLInSeconds': 300, 'botStatus': 'Available', 'creationDateTime': datetime(2015, 1, 1) } stubber.add_response("create_bot", create_bot_response, create_bot_expected_params) # Wait for Bot describe_bot_response = { 'botId': 'testid1234', 'botName': 'testbot', 'description': 'Created by Serverless Bot Framework', 'roleArn': 'arn:aws:iam::123456789012:role/testrole', 'dataPrivacy': { 'childDirected': False }, 'idleSessionTTLInSeconds': 300, 'botStatus': 'Available', 'creationDateTime': datetime(2015, 1, 1), 'lastUpdatedDateTime': datetime(2015, 1, 1) } describe_bot_expected_params = {"botId": "testid1234"} stubber.add_response("describe_bot", describe_bot_response, describe_bot_expected_params) # Create Appointment Bot Locale create_locale_expected_params = { "botId": 'testid1234', "botVersion": 'DRAFT', "localeId": 'en_US', "description": 'created English from lambda', "nluIntentConfidenceThreshold": 0.4 } create_locale_response = { 'botId': 'testid1234', 'botVersion': 'DRAFT', 'localeName': 'en_US', 'localeId': 'en_US', 'description': 'created English from lambda', 'nluIntentConfidenceThreshold': 0.4, 'voiceSettings': { 'voiceId': 'string' }, 'botLocaleStatus': 'NotBuilt', 'creationDateTime': datetime(2015, 1, 1) } stubber.add_response("create_bot_locale", create_locale_response, create_locale_expected_params) # Wait for Locale describe_locale_expected_params = { "botId": "testid1234", "botVersion": "DRAFT", "localeId": "en_US" } describe_locale_response = { 'botId': 'testid1234', 'botVersion': 'DRAFT', 'localeId': 'en_US', 'localeName': 'en_US', 'description': 'created English from lambda', 'nluIntentConfidenceThreshold': 0.4, 'voiceSettings': { 'voiceId': 'string' }, 'intentsCount': 1, 'slotTypesCount': 1, 'botLocaleStatus': 'NotBuilt', 'failureReasons': [], 'creationDateTime': datetime(2015, 1, 1), 'lastUpdatedDateTime': datetime(2015, 1, 1), 'lastBuildSubmittedDateTime': datetime(2015, 1, 1), 'botLocaleHistoryEvents': [ { 'event': 'string', 'eventDate': datetime(2015, 1, 1) }, ] } stubber.add_response("describe_bot_locale", describe_locale_response, describe_locale_expected_params) # Create Appointment Bot Slot Type create_slot_type_expected_params = { "slotTypeName": 'AppointmentTypeValue', "description": 'Types of appointment', "slotTypeValues": [{ 'sampleValue': { 'value': 'cleaning' } }, { 'sampleValue': { 'value': 'root canal' } }, { 'sampleValue': { 'value': 'whitening' } }], "valueSelectionSetting": { 'resolutionStrategy': 'OriginalValue' }, "botId": "testid1234", "botVersion": 'DRAFT', "localeId": "en_US" } create_slot_type_response = { 'slotTypeId': 'AppointmentType', 'slotTypeName': 'AppointmentTypeValue', 'description': 'Types of appointment', 'slotTypeValues': [{ 'sampleValue': { 'value': 'cleaning' } }, { 'sampleValue': { 'value': 'root canal' } }, { 'sampleValue': { 'value': 'whitening' } }], 'valueSelectionSetting': { 'resolutionStrategy': 'OriginalValue' }, 'botId': 'testid1234', 'botVersion': 'DRAFT', 'localeId': 'en_us', 'creationDateTime': datetime(2015, 1, 1) } stubber.add_response("create_slot_type", create_slot_type_response, create_slot_type_expected_params) # Create Appointment Intent create_intent_expected_params = { "intentName": 'MakeAppointment', "botId": 'testid1234', "botVersion": 'DRAFT', "localeId": 'en_US' } create_intent_response = { 'intentId': 'testintentid', 'intentName': 'MakeAppointment', 'description': '', 'parentIntentSignature': '', 'sampleUtterances': [], 'dialogCodeHook': { 'enabled': False }, 'fulfillmentCodeHook': { 'enabled': False }, 'inputContexts': [], 'outputContexts': [], 'botId': 'testid1234', 'botVersion': 'DRAFT', 'localeId': 'en_us', 'creationDateTime': datetime(2015, 1, 1) } stubber.add_response("create_intent", create_intent_response, create_intent_expected_params) # Create Appointment Slot create_slot_time_expected_params = { "slotName": "Time", "description": "Time information.", "slotTypeId": "AMAZON.Time", "valueElicitationSetting": { 'slotConstraint': 'Required', 'promptSpecification': { 'messageGroups': [ { 'message': { 'plainTextMessage': { "value": "At what time should I schedule your appointment?", }, } }, ], 'maxRetries': 5, 'allowInterrupt': True }, }, "obfuscationSetting": { 'obfuscationSettingType': 'None' }, "botId": "testid1234", "botVersion": "DRAFT", "localeId": "en_US", "intentId": "testintentid" } create_slot_time_response = { 'slotId': 'timeslotid', "slotName": "Time", "description": "Time information.", "slotTypeId": "AMAZON.Time", "valueElicitationSetting": { 'slotConstraint': 'Required', 'promptSpecification': { 'messageGroups': [ { 'message': { 'plainTextMessage': { "value": "At what time should I schedule your appointment?", }, } }, ], 'maxRetries': 5, 'allowInterrupt': True }, }, "obfuscationSetting": { 'obfuscationSettingType': 'None' }, "botId": "testid1234", "botVersion": "DRAFT", "localeId": "en_US", "intentId": "testintentid", 'creationDateTime': datetime(2015, 1, 1) } create_slot_date_expected_params = { "slotName": "Date", "description": "Date information.", "slotTypeId": "AMAZON.Date", "valueElicitationSetting": { 'slotConstraint': 'Required', 'promptSpecification': { 'messageGroups': [ { 'message': { 'plainTextMessage': { "value": "When should I schedule your appointment?" }, } }, ], 'maxRetries': 5, 'allowInterrupt': True }, }, "obfuscationSetting": { 'obfuscationSettingType': 'None' }, "botId": "testid1234", "botVersion": "DRAFT", "localeId": "en_US", "intentId": "testintentid" } create_slot_date_response = { 'slotId': 'dateslotid', "slotName": "Date", "description": "Date information.", "slotTypeId": "AMAZON.Date", "valueElicitationSetting": { 'slotConstraint': 'Required', 'promptSpecification': { 'messageGroups': [ { 'message': { 'plainTextMessage': { "value": "When should I schedule your appointment?" }, } }, ], 'maxRetries': 5, 'allowInterrupt': True }, }, "obfuscationSetting": { 'obfuscationSettingType': 'None' }, "botId": "testid1234", "botVersion": "DRAFT", "localeId": "en_US", "intentId": "testintentid", 'creationDateTime': datetime(2015, 1, 1) } create_slot_appointment_type_expected_params = { "slotName": "AppointmentType", "description": "AppointmentType information.", "slotTypeId": "AppointmentType", "valueElicitationSetting": { 'slotConstraint': 'Required', 'promptSpecification': { 'messageGroups': [ { 'message': { 'plainTextMessage': { "value": "What type of appointment would you like to schedule?" }, } }, ], 'maxRetries': 5, 'allowInterrupt': True }, }, "obfuscationSetting": { 'obfuscationSettingType': 'None' }, "botId": "testid1234", "botVersion": "DRAFT", "localeId": "en_US", "intentId": "testintentid" } create_slot_appointment_type_response = { 'slotId': 'AppointmentTypeslotid', "slotName": "AppointmentType", "description": "AppointmentType slot information.", "slotTypeId": "AppointmentType", "valueElicitationSetting": { 'slotConstraint': 'Required', 'promptSpecification': { 'messageGroups': [ { 'message': { 'plainTextMessage': { "value": "What type of appointment would you like to schedule?" }, } }, ], 'maxRetries': 5, 'allowInterrupt': True }, }, "obfuscationSetting": { 'obfuscationSettingType': 'None' }, "botId": "testid1234", "botVersion": "DRAFT", "localeId": "en_US", "intentId": "testintentid", 'creationDateTime': datetime(2015, 1, 1) } stubber.add_response("create_slot", create_slot_time_response, create_slot_time_expected_params) stubber.add_response("create_slot", create_slot_date_response, create_slot_date_expected_params) stubber.add_response("create_slot", create_slot_appointment_type_response, create_slot_appointment_type_expected_params) # Update Appointment Intent update_intent_expected_params = { "intentId": "testintentid", "intentName": 'MakeAppointment', "description": 'MakeAppointment intent created by serverless bot.', "sampleUtterances": [{ 'utterance': 'I would like to book an appointment' }, { 'utterance': 'Book an appointment' }, { 'utterance': 'Book a {AppointmentType}' }], "dialogCodeHook": { 'enabled': False }, "fulfillmentCodeHook": { 'enabled': False }, "intentConfirmationSetting": { 'promptSpecification': { 'messageGroups': [ { 'message': { 'plainTextMessage': { "value": "{Time} is available, should I go ahead and book your appointment?" }, } }, ], 'maxRetries': 5, 'allowInterrupt': True }, 'declinationResponse': { 'messageGroups': [ { 'message': { 'plainTextMessage': { "value": "Okay, I will not schedule an appointment." } } }, ], 'allowInterrupt': True } }, "intentClosingSetting": { 'closingResponse': { 'messageGroups': [ { 'message': { 'plainTextMessage': { "value": "Done." } } }, ], 'allowInterrupt': True } }, "slotPriorities": [ { 'priority': 1, 'slotId': "AppointmentTypeslotid", }, { 'priority': 2, 'slotId': "dateslotid", }, { 'priority': 3, 'slotId': "timeslotid", }, ], "botId": "testid1234", "botVersion": 'DRAFT', "localeId": "en_US" } update_intent_response = { 'intentId': 'testintentid', 'intentName': 'MakeAppointment', 'description': 'MakeAppointment intent created by serverless bot.', "sampleUtterances": [{ 'utterance': 'I would like to book an appointment' }, { 'utterance': 'Book an appointment' }, { 'utterance': 'Book a {AppointmentType}' }], 'dialogCodeHook': { 'enabled': False }, 'fulfillmentCodeHook': { 'enabled': False }, "slotPriorities": [ { 'priority': 1, 'slotId': "AppointmentTypeslotid", }, { 'priority': 2, 'slotId': "dateslotid", }, { 'priority': 3, 'slotId': "timeslotid", }, ], 'botId': 'testid1234', 'botVersion': 'DRAFT', 'localeId': 'en_US', 'creationDateTime': datetime(2015, 1, 1), 'lastUpdatedDateTime': datetime(2015, 1, 1) } stubber.add_response("update_intent", update_intent_response, update_intent_expected_params) # Build Bot Locale build_locale_expected_params = { "botId": "testid1234", "botVersion": "DRAFT", "localeId": "en_US" } build_locale_response = { 'botId': 'testid1234', 'botVersion': 'DRAFT', 'localeId': 'en_US', 'botLocaleStatus': 'Built', 'lastBuildSubmittedDateTime': datetime(2015, 1, 1) } stubber.add_response("build_bot_locale", build_locale_response, build_locale_expected_params) # Wait for Build describe_bot_locale_expected_params = { "botId": "testid1234", "botVersion": "DRAFT", "localeId": "en_US" } describe_bot_locale_response = { 'botId': 'testid1234', 'botVersion': 'DRAFT', 'localeId': 'en_US', 'localeName': 'en_US', 'description': 'created English from lambda', 'nluIntentConfidenceThreshold': 0.4, 'intentsCount': 1, 'slotTypesCount': 1, 'botLocaleStatus': 'Built', 'failureReasons': [], 'creationDateTime': datetime(2015, 1, 1), 'lastUpdatedDateTime': datetime(2015, 1, 1), 'lastBuildSubmittedDateTime': datetime(2015, 1, 1), 'botLocaleHistoryEvents': [ { 'event': 'string', 'eventDate': datetime(2015, 1, 1) }, ] } stubber.add_response("describe_bot_locale", describe_bot_locale_response, describe_bot_locale_expected_params) # Get Bot Alias bot_alias_expected_params = {"botId": "testid1234"} bot_alias_response = { 'botAliasSummaries': [ { 'botAliasId': 'testaliasid', 'botAliasName': 'testalias', 'description': 'string', 'botVersion': 'DRAFT', 'botAliasStatus': 'Available', 'creationDateTime': datetime(2015, 1, 1), 'lastUpdatedDateTime': datetime(2015, 1, 1) }, ], 'nextToken': 'string', 'botId': 'testid1234' } stubber.add_response("list_bot_aliases", bot_alias_response, bot_alias_expected_params) stubber.activate() lambda_function.custom_resource({}, {}) stubber.assert_no_pending_responses()
# or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES # # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions # # and limitations under the License. # ###################################################################################################################### # @author Solution Builders import os import time import json import random import logging import datetime from shared.client import get_client from pizza_order.pizza_responses import get_fulfilled_message dynamodb = get_client("dynamodb") logger = logging.getLogger() logger.setLevel(logging.INFO) def empty_slots(intent_request): ''' Checks if all intent slots values are empty. :param intent_request: Event object that was sent by Amazon Lex :returns: True if all slots are empty and False if not. ''' slots = intent_request['sessionState']['intent']['slots'] for slot_name in slots: if slots[slot_name] != None: return False
# with the License. A copy of the License is located at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES # # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions # # and limitations under the License. # ###################################################################################################################### import os import logging from random import randint import requests from shared.client import get_client logger = logging.getLogger(__name__) ssm = get_client("ssm") api_provider = os.environ.get("API_PROVIDER", False) ssm_key = os.environ.get("SSM_REFERENCE_TO_API_KEY", "") api_key = "" if api_provider: try: api_key = ssm.get_parameter(Name=ssm_key, WithDecryption=True)["Parameter"]["Value"] except Exception as e: logger.error("Parameter not found in SSM") logger.error(e) api_key = ""
def test_place_order( self, mock_calculate_bill, mock_respond, mock_get_fulfilled_message, mock_time, ): from pizza_order.pizza_helpers import place_order from shared.client import get_client intent_request = { "requestAttributes": { "email": "*****@*****.**" }, "sessionState": { "intent": { "slots": { "type": { "value": { "resolvedValues": ["testType"] } }, "size": { "value": { "resolvedValues": ["testSize"] } }, "crust": { "value": { "resolvedValues": ["testCrust"] } }, "count": { "value": { "resolvedValues": ["1234"] } }, } } }, "bot": { "localeId": "en_US" }, } dynamo_client = get_client("dynamodb") stubber = Stubber(dynamo_client) mock_logger = Mock() dynamo_expected_params = { "TableName": "test_table", "Item": { "orderId": { "S": "1234" }, "orderTimestamp": { "N": "1234" }, "customerId": { "S": "*****@*****.**" }, "pizzaType": { "S": "testType" }, "pizzaSize": { "S": "testSize" }, "pizzaCrust": { "S": "testCrust" }, "pizzaCount": { "N": "1234" }, "botLanguage": { "S": "en_US" }, "orderTotalBill": { "N": "1234" }, }, } dynamo_response = { "Attributes": { "orderId": { "S": "1234" }, "orderTimestamp": { "N": "1234" }, "customerId": { "S": "*****@*****.**" }, "pizzaType": { "S": "testType" }, "pizzaSize": { "S": "testSize" }, "pizzaCrust": { "S": "testCrust" }, "pizzaCount": { "N": "1234" }, "botLanguage": { "S": "en_US" }, "orderTotalBill": { "N": "1234.56" }, }, } stubber.add_response("put_item", dynamo_response, dynamo_expected_params) with stubber: place_order(intent_request, "1234", mock_logger) mock_respond.assert_called_with( intent_request, message="test message", fulfillment_state="Fulfilled", dialog_action_type="Close", ) mock_logger.info.assert_called_with( 'Placed order with order ID: 1234') stubber.assert_no_pending_responses()
def test_save_feedback(self, mocked_close, mocked_uuid): from shared.client import get_client from leave_feedback.leave_feedback_handler import save_feedback intent_request = { "sessionState": { "intent": { "slots": { "firstName": { "value": { "interpretedValue": "testname" } }, "lastName": { "value": { "interpretedValue": "testlastname" } }, "feedback": { "value": { "interpretedValue": "testfeedback" } }, } } } } # Setting up boto3 client stubber dynamo_client = get_client("dynamodb") stubber = Stubber(dynamo_client) dynamo_expected_params = { "TableName": "testtable", "Item": { "uuid": { "S": "1234" }, "FirstName": { "S": "testname" }, "LastName": { "S": "testlastname" }, "Feedback": { "S": "testfeedback" }, }, } dynamo_response = { "Attributes": { "uuid": { "S": "1234" }, "FirstName": { "S": "testname" }, "LastName": { "S": "testlastname" }, "Feedback": { "S": "testfeedback" }, }, } stubber.add_response("put_item", dynamo_response, dynamo_expected_params) # Calling function and assertions with stubber: save_feedback(intent_request) mocked_close.assert_called_with(intent_request, "Fulfilled") mocked_uuid.assert_called() stubber.assert_no_pending_responses() stubber.add_client_error("put_item", "ResourceNotFoundException", "Specified Table does not exist") with stubber: save_feedback(intent_request) mocked_close.assert_called_with(intent_request, "Failed")
# and limitations under the License. # ###################################################################################################################### import os from time import sleep import boto3 from crhelper import CfnResource from shared.logger import get_logger from shared.client import get_client from helpers import (detect_locale, clarification_prompt, slot_types, abort_statement, utterances, confirmation_prompt, decline_reponse, closing_response, slot_message) logger = get_logger(__name__) helper = CfnResource(json_logging=True, log_level="INFO") client = get_client('lexv2-models') global_bot_id = '' def wait_for_bot(bot_id): response = client.describe_bot(botId=bot_id) bot_status = response['botStatus'] while (bot_status == 'Creating'): sleep(1) response = client.describe_bot(botId=bot_id) bot_status = response['botStatus'] if bot_status != 'Available': logger.error(response) raise RuntimeError("Failed to create Lex bot.")