From fab1d1256918d51c344ab596113e7dfd45cca377 Mon Sep 17 00:00:00 2001 From: Steven Gum Date: Thu, 5 Jul 2018 13:46:31 -0700 Subject: [PATCH] rename BotContext to TurnContext --- .../generators/app/templates/main.py | 10 ++--- .../botbuilder/core/__init__.py | 4 +- .../botbuilder/core/bot_adapter.py | 10 ++--- .../botbuilder/core/bot_framework_adapter.py | 20 +++++----- .../botbuilder/core/bot_state.py | 10 ++--- .../botbuilder/core/conversation_state.py | 4 +- .../botbuilder/core/middleware_set.py | 10 ++--- .../botbuilder/core/storage.py | 4 +- .../botbuilder/core/test_adapter.py | 4 +- .../core/{bot_context.py => turn_context.py} | 36 ++++++++--------- .../botbuilder/core/user_state.py | 4 +- .../botbuilder-core/tests/test_bot_state.py | 4 +- .../tests/test_conversation_state.py | 8 ++-- .../tests/test_test_adapter.py | 26 ++++++------ ...st_bot_context.py => test_turn_context.py} | 40 +++++++++---------- .../botbuilder-core/tests/test_user_state.py | 8 ++-- .../adapter/console_adapter.py | 16 ++++---- samples/Console-EchoBot/main.py | 4 +- samples/EchoBot-with-State/main.py | 8 ++-- samples/Rich-Cards-Bot/main.py | 10 ++--- 20 files changed, 120 insertions(+), 120 deletions(-) rename libraries/botbuilder-core/botbuilder/core/{bot_context.py => turn_context.py} (85%) rename libraries/botbuilder-core/tests/{test_bot_context.py => test_turn_context.py} (87%) diff --git a/Generator/generator-botbuilder-python/generators/app/templates/main.py b/Generator/generator-botbuilder-python/generators/app/templates/main.py index b6ae518c6..c1c4d7963 100644 --- a/Generator/generator-botbuilder-python/generators/app/templates/main.py +++ b/Generator/generator-botbuilder-python/generators/app/templates/main.py @@ -3,7 +3,7 @@ from aiohttp import web from botbuilder.schema import (Activity, ActivityTypes) -from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, BotContext) +from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, TurnContext) APP_ID = '' APP_PASSWORD = '' @@ -23,13 +23,13 @@ async def create_reply_activity(request_activity, text) -> Activity: service_url=request_activity.service_url) -async def handle_message(context: BotContext) -> web.Response: +async def handle_message(context: TurnContext) -> web.Response: response = await create_reply_activity(context.request, 'You said %s.' % context.request.text) await context.send_activity(response) return web.Response(status=202) -async def handle_conversation_update(context: BotContext) -> web.Response: +async def handle_conversation_update(context: TurnContext) -> web.Response: if context.request.members_added[0].id != context.request.recipient.id: response = await create_reply_activity(context.request, 'Welcome to the Echo Adapter Bot!') await context.send_activity(response) @@ -40,7 +40,7 @@ async def unhandled_activity() -> web.Response: return web.Response(status=404) -async def request_handler(context: BotContext) -> web.Response: +async def request_handler(context: TurnContext) -> web.Response: if context.request.type == 'message': return await handle_message(context) elif context.request.type == 'conversationUpdate': @@ -65,4 +65,4 @@ async def messages(req: web.web_request) -> web.Response: try: web.run_app(app, host='localhost', port=PORT) except Exception as e: - raise e \ No newline at end of file + raise e diff --git a/libraries/botbuilder-core/botbuilder/core/__init__.py b/libraries/botbuilder-core/botbuilder/core/__init__.py index 55785c607..53d6558f6 100644 --- a/libraries/botbuilder-core/botbuilder/core/__init__.py +++ b/libraries/botbuilder-core/botbuilder/core/__init__.py @@ -9,7 +9,7 @@ from .bot_adapter import BotAdapter from .bot_framework_adapter import BotFrameworkAdapter, BotFrameworkAdapterSettings -from .bot_context import BotContext +from .turn_context import TurnContext from .bot_state import BotState from .card_factory import CardFactory from .conversation_state import ConversationState @@ -22,7 +22,7 @@ __all__ = ['AnonymousReceiveMiddleware', 'BotAdapter', - 'BotContext', + 'TurnContext', 'BotFrameworkAdapter', 'BotFrameworkAdapterSettings', 'BotState', diff --git a/libraries/botbuilder-core/botbuilder/core/bot_adapter.py b/libraries/botbuilder-core/botbuilder/core/bot_adapter.py index 306b23c11..83868375c 100644 --- a/libraries/botbuilder-core/botbuilder/core/bot_adapter.py +++ b/libraries/botbuilder-core/botbuilder/core/bot_adapter.py @@ -5,7 +5,7 @@ from typing import List, Callable from botbuilder.schema import Activity, ConversationReference -from .bot_context import BotContext +from .turn_context import TurnContext from .middleware_set import MiddlewareSet @@ -14,7 +14,7 @@ def __init__(self): self._middleware = MiddlewareSet() @abstractmethod - async def send_activities(self, context: BotContext, activities: List[Activity]): + async def send_activities(self, context: TurnContext, activities: List[Activity]): """ Sends a set of activities to the user. An array of responses from the server will be returned. :param activities: @@ -23,7 +23,7 @@ async def send_activities(self, context: BotContext, activities: List[Activity]) raise NotImplementedError() @abstractmethod - async def update_activity(self, context: BotContext, activity: Activity): + async def update_activity(self, context: TurnContext, activity: Activity): """ Replaces an existing activity. :param activity: @@ -32,7 +32,7 @@ async def update_activity(self, context: BotContext, activity: Activity): raise NotImplementedError() @abstractmethod - async def delete_activity(self, context: BotContext, reference: ConversationReference): + async def delete_activity(self, context: TurnContext, reference: ConversationReference): """ Deletes an existing activity. :param reference: @@ -48,7 +48,7 @@ def use(self, middleware): """ self._middleware.use(middleware) - async def run_middleware(self, context: BotContext, callback: Callable=None): + async def run_middleware(self, context: TurnContext, callback: Callable=None): """ Called by the parent class to run the adapters middleware set and calls the passed in `callback()` handler at the end of the chain. diff --git a/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py b/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py index 7e099ad88..c7842e1ef 100644 --- a/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py +++ b/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py @@ -13,7 +13,7 @@ from . import __version__ from .bot_adapter import BotAdapter -from .bot_context import BotContext +from .turn_context import TurnContext USER_AGENT = f"Microsoft-BotFramework/3.1 (BotBuilder Python/{__version__})" @@ -42,7 +42,7 @@ async def continue_conversation(self, reference: ConversationReference, logic): :param logic: :return: """ - request = BotContext.apply_conversation_reference(Activity(), reference, is_incoming=True) + request = TurnContext.apply_conversation_reference(Activity(), reference, is_incoming=True) context = self.create_context(request) return await self.run_middleware(context, logic) @@ -63,7 +63,7 @@ async def create_conversation(self, reference: ConversationReference, logic): client = self.create_connector_client(reference.service_url) resource_response = await client.conversations.create_conversation_async(parameters) - request = BotContext.apply_conversation_reference(Activity(), reference, is_incoming=True) + request = TurnContext.apply_conversation_reference(Activity(), reference, is_incoming=True) request.conversation = ConversationAccount(id=resource_response.id) if resource_response.service_url: request.service_url = resource_response.service_url @@ -107,7 +107,7 @@ def create_context(self, activity): :param activity: :return: """ - return BotContext(self, activity) + return TurnContext(self, activity) @staticmethod async def parse_request(req): @@ -148,7 +148,7 @@ async def validate_activity(activity: Activity): if is_valid_activity: return req - async def update_activity(self, context: BotContext, activity: Activity): + async def update_activity(self, context: TurnContext, activity: Activity): """ Replaces an activity that was previously sent to a channel. It should be noted that not all channels support this feature. @@ -165,7 +165,7 @@ async def update_activity(self, context: BotContext, activity: Activity): except Exception as e: raise e - async def delete_activity(self, context: BotContext, conversation_reference: ConversationReference): + async def delete_activity(self, context: TurnContext, conversation_reference: ConversationReference): """ Deletes an activity that was previously sent to a channel. It should be noted that not all channels support this feature. @@ -180,7 +180,7 @@ async def delete_activity(self, context: BotContext, conversation_reference: Con except Exception as e: raise e - async def send_activities(self, context: BotContext, activities: List[Activity]): + async def send_activities(self, context: TurnContext, activities: List[Activity]): try: for activity in activities: if activity.type == 'delay': @@ -198,7 +198,7 @@ async def send_activities(self, context: BotContext, activities: List[Activity]) except Exception as e: raise e - async def delete_conversation_member(self, context: BotContext, member_id: str) -> None: + async def delete_conversation_member(self, context: TurnContext, member_id: str) -> None: """ Deletes a member from the current conversation. :param context: @@ -220,7 +220,7 @@ async def delete_conversation_member(self, context: BotContext, member_id: str) except Exception as e: raise e - async def get_activity_members(self, context: BotContext, activity_id: str): + async def get_activity_members(self, context: TurnContext, activity_id: str): """ Lists the members of a given activity. :param context: @@ -244,7 +244,7 @@ async def get_activity_members(self, context: BotContext, activity_id: str): except Exception as e: raise e - async def get_conversation_members(self, context: BotContext): + async def get_conversation_members(self, context: TurnContext): """ Lists the members of a current conversation. :param context: diff --git a/libraries/botbuilder-core/botbuilder/core/bot_state.py b/libraries/botbuilder-core/botbuilder/core/bot_state.py index c597d8c31..02918a90e 100644 --- a/libraries/botbuilder-core/botbuilder/core/bot_state.py +++ b/libraries/botbuilder-core/botbuilder/core/bot_state.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from .bot_context import BotContext +from .turn_context import TurnContext from .middleware_set import Middleware from .storage import calculate_change_hash, StoreItem, StorageKeyFactory, Storage @@ -27,7 +27,7 @@ async def on_process_request(self, context, next_middleware): await self.write(context) return logic_results - async def read(self, context: BotContext, force: bool=False): + async def read(self, context: TurnContext, force: bool=False): """ Reads in and caches the current state object for a turn. :param context: @@ -47,7 +47,7 @@ async def read(self, context: BotContext, force: bool=False): return cached['state'] - async def write(self, context: BotContext, force: bool=False): + async def write(self, context: TurnContext, force: bool=False): """ Saves the cached state object if it's been changed. :param context: @@ -67,7 +67,7 @@ async def write(self, context: BotContext, force: bool=False): cached['hash'] = calculate_change_hash(cached['state']) context.services[self.state_key] = cached - async def clear(self, context: BotContext): + async def clear(self, context: TurnContext): """ Clears the current state object for a turn. :param context: @@ -78,7 +78,7 @@ async def clear(self, context: BotContext): cached['state'] = StoreItem() context.services[self.state_key] = cached - async def get(self, context: BotContext): + async def get(self, context: TurnContext): """ Returns a cached state object or undefined if not cached. :param context: diff --git a/libraries/botbuilder-core/botbuilder/core/conversation_state.py b/libraries/botbuilder-core/botbuilder/core/conversation_state.py index 1fa1fdd19..a1684dbe6 100644 --- a/libraries/botbuilder-core/botbuilder/core/conversation_state.py +++ b/libraries/botbuilder-core/botbuilder/core/conversation_state.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from .bot_context import BotContext +from .turn_context import TurnContext from .bot_state import BotState from .storage import Storage @@ -30,7 +30,7 @@ def call_get_storage_key(context): super(ConversationState, self).__init__(storage, call_get_storage_key) self.namespace = namespace - def get_storage_key(self, context: BotContext): + def get_storage_key(self, context: TurnContext): activity = context.activity channel_id = getattr(activity, 'channel_id', None) conversation_id = getattr(activity.conversation, 'id', None) if hasattr(activity, 'conversation') else None diff --git a/libraries/botbuilder-core/botbuilder/core/middleware_set.py b/libraries/botbuilder-core/botbuilder/core/middleware_set.py index de889e1b3..6c74e22b0 100644 --- a/libraries/botbuilder-core/botbuilder/core/middleware_set.py +++ b/libraries/botbuilder-core/botbuilder/core/middleware_set.py @@ -4,12 +4,12 @@ from asyncio import iscoroutinefunction from abc import ABC, abstractmethod -from .bot_context import BotContext +from .turn_context import TurnContext class Middleware(ABC): @abstractmethod - def on_process_request(self, context: BotContext, next): pass + def on_process_request(self, context: TurnContext, next): pass class AnonymousReceiveMiddleware(Middleware): @@ -18,7 +18,7 @@ def __init__(self, anonymous_handler): raise TypeError('AnonymousReceiveMiddleware must be instantiated with a valid coroutine function.') self._to_call = anonymous_handler - def on_process_request(self, context: BotContext, next): + def on_process_request(self, context: TurnContext, next): return self._to_call(context, next) @@ -45,14 +45,14 @@ def use(self, *middleware: Middleware): else: raise TypeError('MiddlewareSet.use(): invalid middleware at index "%s" being added.' % idx) - async def receive_activity(self, context: BotContext): + async def receive_activity(self, context: TurnContext): await self.receive_activity_internal(context, None) async def on_process_request(self, context, logic): await self.receive_activity_internal(context, None) await logic() - async def receive_activity_with_status(self, context: BotContext, callback): + async def receive_activity_with_status(self, context: TurnContext, callback): return await self.receive_activity_internal(context, callback) async def receive_activity_internal(self, context, callback, next_middleware_index=0): diff --git a/libraries/botbuilder-core/botbuilder/core/storage.py b/libraries/botbuilder-core/botbuilder/core/storage.py index d9be6ae67..b1fe3d3e6 100644 --- a/libraries/botbuilder-core/botbuilder/core/storage.py +++ b/libraries/botbuilder-core/botbuilder/core/storage.py @@ -5,7 +5,7 @@ from abc import ABC, abstractmethod from typing import Callable, List -from .bot_context import BotContext +from .turn_context import TurnContext class Storage(ABC): @@ -54,7 +54,7 @@ def __str__(self): return output -StorageKeyFactory = Callable[[BotContext], str] +StorageKeyFactory = Callable[[TurnContext], str] def calculate_change_hash(item: StoreItem) -> str: diff --git a/libraries/botbuilder-core/botbuilder/core/test_adapter.py b/libraries/botbuilder-core/botbuilder/core/test_adapter.py index b54c90586..3cd64ee40 100644 --- a/libraries/botbuilder-core/botbuilder/core/test_adapter.py +++ b/libraries/botbuilder-core/botbuilder/core/test_adapter.py @@ -6,7 +6,7 @@ from datetime import datetime from typing import Coroutine, List from copy import copy -from botbuilder.core import BotAdapter, BotContext +from botbuilder.core import BotAdapter, TurnContext from botbuilder.schema import (ActivityTypes, Activity, ConversationAccount, ConversationReference, ChannelAccount, ResourceResponse) @@ -109,7 +109,7 @@ async def receive_activity(self, activity): request.id = str(self._next_id) # Create context object and run middleware - context = BotContext(self, request) + context = TurnContext(self, request) return await self.run_middleware(context, self.logic) async def send(self, user_says): diff --git a/libraries/botbuilder-core/botbuilder/core/bot_context.py b/libraries/botbuilder-core/botbuilder/core/turn_context.py similarity index 85% rename from libraries/botbuilder-core/botbuilder/core/bot_context.py rename to libraries/botbuilder-core/botbuilder/core/turn_context.py index 5a76335df..2bc6bbba1 100644 --- a/libraries/botbuilder-core/botbuilder/core/bot_context.py +++ b/libraries/botbuilder-core/botbuilder/core/turn_context.py @@ -8,14 +8,14 @@ from botbuilder.schema import Activity, ConversationReference, ResourceResponse -class BotContext(object): +class TurnContext(object): def __init__(self, adapter_or_context, request: Activity=None): """ - Creates a new BotContext instance. + Creates a new TurnContext instance. :param adapter_or_context: :param request: """ - if isinstance(adapter_or_context, BotContext): + if isinstance(adapter_or_context, TurnContext): adapter_or_context.copy_to(self) else: self.adapter = adapter_or_context @@ -28,11 +28,11 @@ def __init__(self, adapter_or_context, request: Activity=None): self._responded = {'responded': False} if self.adapter is None: - raise TypeError('BotContext must be instantiated with an adapter.') + raise TypeError('TurnContext must be instantiated with an adapter.') if self.activity is None: - raise TypeError('BotContext must be instantiated with a request parameter of type Activity.') + raise TypeError('TurnContext must be instantiated with a request parameter of type Activity.') - def copy_to(self, context: 'BotContext') -> None: + def copy_to(self, context: 'TurnContext') -> None: """ Called when this TurnContext instance is passed into the constructor of a new TurnContext instance. Can be overridden in derived classes. @@ -54,12 +54,12 @@ def activity(self): @activity.setter def activity(self, value): """ - Used to set BotContext._activity when a context object is created. Only takes instances of Activities. + Used to set TurnContext._activity when a context object is created. Only takes instances of Activities. :param value: :return: """ if not isinstance(value, Activity): - raise TypeError('BotContext: cannot set `activity` to a type other than Activity.') + raise TypeError('TurnContext: cannot set `activity` to a type other than Activity.') else: self._activity = value @@ -74,7 +74,7 @@ def responded(self): @responded.setter def responded(self, value): if not value: - raise ValueError('BotContext: cannot set BotContext.responded to False.') + raise ValueError('TurnContext: cannot set TurnContext.responded to False.') else: self._responded['responded'] = True @@ -92,7 +92,7 @@ def get(self, key: str) -> object: try: return self._services[key] except KeyError: - raise KeyError('%s not found in BotContext._services.' % key) + raise KeyError('%s not found in TurnContext._services.' % key) def has(self, key: str) -> bool: """ @@ -122,14 +122,14 @@ async def send_activity(self, *activity_or_text: Union[Activity, str]) -> Resour :param activity_or_text: :return: """ - reference = BotContext.get_conversation_reference(self.activity) - output = [BotContext.apply_conversation_reference( + reference = TurnContext.get_conversation_reference(self.activity) + output = [TurnContext.apply_conversation_reference( Activity(text=a, type='message') if isinstance(a, str) else a, reference) for a in activity_or_text] for activity in output: activity.input_hint = 'acceptingInput' - async def callback(context: 'BotContext', output): + async def callback(context: 'TurnContext', output): responses = await context.adapter.send_activities(context, output) context._responded = True return responses @@ -151,13 +151,13 @@ async def delete_activity(self, id_or_reference: Union[str, ConversationReferenc :return: """ if type(id_or_reference) == str: - reference = BotContext.get_conversation_reference(self.activity) + reference = TurnContext.get_conversation_reference(self.activity) reference.activity_id = id_or_reference else: reference = id_or_reference return await self._emit(self._on_delete_activity, reference, self.adapter.delete_activity(self, reference)) - def on_send_activities(self, handler) -> 'BotContext': + def on_send_activities(self, handler) -> 'TurnContext': """ Registers a handler to be notified of and potentially intercept the sending of activities. :param handler: @@ -166,7 +166,7 @@ def on_send_activities(self, handler) -> 'BotContext': self._on_send_activities.append(handler) return self - def on_update_activity(self, handler) -> 'BotContext': + def on_update_activity(self, handler) -> 'TurnContext': """ Registers a handler to be notified of and potentially intercept an activity being updated. :param handler: @@ -175,7 +175,7 @@ def on_update_activity(self, handler) -> 'BotContext': self._on_update_activity.append(handler) return self - def on_delete_activity(self, handler) -> 'BotContext': + def on_delete_activity(self, handler) -> 'TurnContext': """ Registers a handler to be notified of and potentially intercept an activity being deleted. :param handler: @@ -208,7 +208,7 @@ def get_conversation_reference(activity: Activity) -> ConversationReference: object and then later used to message the user proactively. Usage Example: - reference = BotContext.get_conversation_reference(context.request) + reference = TurnContext.get_conversation_reference(context.request) :param activity: :return: """ diff --git a/libraries/botbuilder-core/botbuilder/core/user_state.py b/libraries/botbuilder-core/botbuilder/core/user_state.py index 190226072..9bc0d1258 100644 --- a/libraries/botbuilder-core/botbuilder/core/user_state.py +++ b/libraries/botbuilder-core/botbuilder/core/user_state.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from .bot_context import BotContext +from .turn_context import TurnContext from .bot_state import BotState from .storage import Storage @@ -30,7 +30,7 @@ def call_get_storage_key(context): super(UserState, self).__init__(storage, call_get_storage_key) - def get_storage_key(self, context: BotContext) -> str: + def get_storage_key(self, context: TurnContext) -> str: """ Returns the storage key for the current user state. :param context: diff --git a/libraries/botbuilder-core/tests/test_bot_state.py b/libraries/botbuilder-core/tests/test_bot_state.py index baa26cb6e..3ecba5c6d 100644 --- a/libraries/botbuilder-core/tests/test_bot_state.py +++ b/libraries/botbuilder-core/tests/test_bot_state.py @@ -3,7 +3,7 @@ import pytest -from botbuilder.core import BotContext, BotState, MemoryStorage, TestAdapter +from botbuilder.core import TurnContext, BotState, MemoryStorage, TestAdapter from botbuilder.schema import Activity RECEIVED_MESSAGE = Activity(type='message', @@ -24,7 +24,7 @@ def key_factory(context): class TestBotState: storage = MemoryStorage() adapter = TestAdapter() - context = BotContext(adapter, RECEIVED_MESSAGE) + context = TurnContext(adapter, RECEIVED_MESSAGE) middleware = BotState(storage, key_factory) @pytest.mark.asyncio diff --git a/libraries/botbuilder-core/tests/test_conversation_state.py b/libraries/botbuilder-core/tests/test_conversation_state.py index 01e386aa7..0be80f1ba 100644 --- a/libraries/botbuilder-core/tests/test_conversation_state.py +++ b/libraries/botbuilder-core/tests/test_conversation_state.py @@ -3,7 +3,7 @@ import pytest -from botbuilder.core import BotContext, MemoryStorage, TestAdapter, ConversationState +from botbuilder.core import TurnContext, MemoryStorage, TestAdapter, ConversationState from botbuilder.schema import Activity, ConversationAccount RECEIVED_MESSAGE = Activity(type='message', @@ -24,7 +24,7 @@ class TestConversationState: storage = MemoryStorage() adapter = TestAdapter() - context = BotContext(adapter, RECEIVED_MESSAGE) + context = TurnContext(adapter, RECEIVED_MESSAGE) middleware = ConversationState(storage) @pytest.mark.asyncio @@ -62,7 +62,7 @@ async def next_middleware(): @pytest.mark.asyncio async def test_should_reject_with_error_if_channel_id_is_missing(self): - context = BotContext(self.adapter, MISSING_CHANNEL_ID) + context = TurnContext(self.adapter, MISSING_CHANNEL_ID) async def next_middleware(): assert False, 'should not have called next_middleware' @@ -78,7 +78,7 @@ async def next_middleware(): @pytest.mark.asyncio async def test_should_reject_with_error_if_conversation_is_missing(self): - context = BotContext(self.adapter, MISSING_CONVERSATION) + context = TurnContext(self.adapter, MISSING_CONVERSATION) async def next_middleware(): assert False, 'should not have called next_middleware' diff --git a/libraries/botbuilder-core/tests/test_test_adapter.py b/libraries/botbuilder-core/tests/test_test_adapter.py index 1a22f6bf9..3a94cf014 100644 --- a/libraries/botbuilder-core/tests/test_test_adapter.py +++ b/libraries/botbuilder-core/tests/test_test_adapter.py @@ -3,7 +3,7 @@ import pytest from botbuilder.schema import Activity, ConversationReference -from botbuilder.core import BotContext, TestAdapter +from botbuilder.core import TurnContext, TestAdapter from datetime import datetime RECEIVED_MESSAGE = Activity(type='message', text='received') @@ -14,7 +14,7 @@ class TestTestAdapter: @pytest.mark.asyncio async def test_should_call_bog_logic_when_receive_activity_is_called(self): - async def logic(context: BotContext): + async def logic(context: TurnContext): assert context assert context.activity assert context.activity.type == 'message' @@ -30,7 +30,7 @@ async def logic(context: BotContext): @pytest.mark.asyncio async def test_should_support_receive_activity_with_activity(self): - async def logic(context: BotContext): + async def logic(context: TurnContext): assert context.activity.type == 'message' assert context.activity.text == 'test' adapter = TestAdapter(logic) @@ -38,7 +38,7 @@ async def logic(context: BotContext): @pytest.mark.asyncio async def test_should_set_activity_type_when_receive_activity_receives_activity_without_type(self): - async def logic(context: BotContext): + async def logic(context: TurnContext): assert context.activity.type == 'message' assert context.activity.text == 'test' adapter = TestAdapter(logic) @@ -46,7 +46,7 @@ async def logic(context: BotContext): @pytest.mark.asyncio async def test_should_support_custom_activity_id_in_receive_activity(self): - async def logic(context: BotContext): + async def logic(context: TurnContext): assert context.activity.id == 'myId' assert context.activity.type == 'message' assert context.activity.text == 'test' @@ -55,21 +55,21 @@ async def logic(context: BotContext): @pytest.mark.asyncio async def test_should_call_bot_logic_when_send_is_called(self): - async def logic(context: BotContext): + async def logic(context: TurnContext): assert context.activity.text == 'test' adapter = TestAdapter(logic) await adapter.send('test') @pytest.mark.asyncio async def test_should_send_and_receive_when_test_is_called(self): - async def logic(context: BotContext): + async def logic(context: TurnContext): await context.send_activity(RECEIVED_MESSAGE) adapter = TestAdapter(logic) await adapter.test('test', 'received') @pytest.mark.asyncio async def test_should_send_and_throw_assertion_error_when_test_is_called(self): - async def logic(context: BotContext): + async def logic(context: TurnContext): await context.send_activity(RECEIVED_MESSAGE) adapter = TestAdapter(logic) try: @@ -83,7 +83,7 @@ async def logic(context: BotContext): async def test_tests_should_call_test_for_each_tuple(self): counter = 0 - async def logic(context: BotContext): + async def logic(context: TurnContext): nonlocal counter counter += 1 await context.send_activity(Activity(type='message', text=str(counter))) @@ -96,7 +96,7 @@ async def logic(context: BotContext): async def test_tests_should_call_test_for_each_list(self): counter = 0 - async def logic(context: BotContext): + async def logic(context: TurnContext): nonlocal counter counter += 1 await context.send_activity(Activity(type='message', text=str(counter))) @@ -107,7 +107,7 @@ async def logic(context: BotContext): @pytest.mark.asyncio async def test_should_assert_reply_after_send(self): - async def logic(context: BotContext): + async def logic(context: TurnContext): await context.send_activity(RECEIVED_MESSAGE) adapter = TestAdapter(logic) @@ -116,7 +116,7 @@ async def logic(context: BotContext): @pytest.mark.asyncio async def test_should_support_context_update_activity_call(self): - async def logic(context: BotContext): + async def logic(context: TurnContext): await context.update_activity(UPDATED_ACTIVITY) await context.send_activity(RECEIVED_MESSAGE) @@ -127,7 +127,7 @@ async def logic(context: BotContext): @pytest.mark.asyncio async def test_should_support_context_delete_activity_call(self): - async def logic(context: BotContext): + async def logic(context: TurnContext): await context.delete_activity(DELETED_ACTIVITY_REFERENCE) await context.send_activity(RECEIVED_MESSAGE) diff --git a/libraries/botbuilder-core/tests/test_bot_context.py b/libraries/botbuilder-core/tests/test_turn_context.py similarity index 87% rename from libraries/botbuilder-core/tests/test_bot_context.py rename to libraries/botbuilder-core/tests/test_turn_context.py index 9afc4b68d..7d9d6987b 100644 --- a/libraries/botbuilder-core/tests/test_bot_context.py +++ b/libraries/botbuilder-core/tests/test_turn_context.py @@ -4,7 +4,7 @@ import pytest from botbuilder.schema import Activity, ChannelAccount, ResourceResponse, ConversationAccount -from botbuilder.core import BotAdapter, BotContext +from botbuilder.core import BotAdapter, TurnContext ACTIVITY = Activity(id='1234', type='message', text='test', @@ -41,11 +41,11 @@ async def delete_activity(self, context, reference): class TestBotContext: def test_should_create_context_with_request_and_adapter(self): - context = BotContext(SimpleAdapter(), ACTIVITY) + context = TurnContext(SimpleAdapter(), ACTIVITY) def test_should_not_create_context_without_request(self): try: - context = BotContext(SimpleAdapter(), None) + context = TurnContext(SimpleAdapter(), None) except TypeError: pass except Exception as e: @@ -53,20 +53,20 @@ def test_should_not_create_context_without_request(self): def test_should_not_create_context_without_adapter(self): try: - context = BotContext(None, ACTIVITY) + context = TurnContext(None, ACTIVITY) except TypeError: pass except Exception as e: raise e def test_should_create_context_with_older_context(self): - context = BotContext(SimpleAdapter(), ACTIVITY) - new_context = BotContext(context) + context = TurnContext(SimpleAdapter(), ACTIVITY) + new_context = TurnContext(context) def test_copy_to_should_copy_all_references(self): old_adapter = SimpleAdapter() old_activity = Activity(id='2', type='message', text='test copy') - old_context = BotContext(old_adapter, old_activity) + old_context = TurnContext(old_adapter, old_activity) old_context.responded = True async def send_activities_handler(context, activities, next_handler): @@ -92,7 +92,7 @@ async def update_activity_handler(context, activity, next_handler): old_context.on_update_activity(update_activity_handler) adapter = SimpleAdapter() - new_context = BotContext(adapter, ACTIVITY) + new_context = TurnContext(adapter, ACTIVITY) assert len(new_context._on_send_activities) == 0 assert len(new_context._on_update_activity) == 0 assert len(new_context._on_delete_activity) == 0 @@ -107,17 +107,17 @@ async def update_activity_handler(context, activity, next_handler): assert len(new_context._on_delete_activity) == 1 def test_responded_should_be_automatically_set_to_False(self): - context = BotContext(SimpleAdapter(), ACTIVITY) + context = TurnContext(SimpleAdapter(), ACTIVITY) assert context.responded is False def test_should_be_able_to_set_responded_to_True(self): - context = BotContext(SimpleAdapter(), ACTIVITY) + context = TurnContext(SimpleAdapter(), ACTIVITY) assert context.responded is False context.responded = True assert context.responded def test_should_not_be_able_to_set_responded_to_False(self): - context = BotContext(SimpleAdapter(), ACTIVITY) + context = TurnContext(SimpleAdapter(), ACTIVITY) try: context.responded = False except ValueError: @@ -127,7 +127,7 @@ def test_should_not_be_able_to_set_responded_to_False(self): @pytest.mark.asyncio async def test_should_call_on_delete_activity_handlers_before_deletion(self): - context = BotContext(SimpleAdapter(), ACTIVITY) + context = TurnContext(SimpleAdapter(), ACTIVITY) called = False async def delete_handler(context, reference, next_handler_coroutine): @@ -144,7 +144,7 @@ async def delete_handler(context, reference, next_handler_coroutine): @pytest.mark.asyncio async def test_should_call_multiple_on_delete_activity_handlers_in_order(self): - context = BotContext(SimpleAdapter(), ACTIVITY) + context = TurnContext(SimpleAdapter(), ACTIVITY) called_first = False called_second = False @@ -176,7 +176,7 @@ async def second_delete_handler(context, reference, next_handler_coroutine): @pytest.mark.asyncio async def test_should_call_send_on_activities_handler_before_send(self): - context = BotContext(SimpleAdapter(), ACTIVITY) + context = TurnContext(SimpleAdapter(), ACTIVITY) called = False async def send_handler(context, activities, next_handler_coroutine): @@ -193,7 +193,7 @@ async def send_handler(context, activities, next_handler_coroutine): @pytest.mark.asyncio async def test_should_call_on_update_activity_handler_before_update(self): - context = BotContext(SimpleAdapter(), ACTIVITY) + context = TurnContext(SimpleAdapter(), ACTIVITY) called = False async def update_handler(context, activity, next_handler_coroutine): @@ -209,7 +209,7 @@ async def update_handler(context, activity, next_handler_coroutine): assert called is True def test_get_conversation_reference_should_return_valid_reference(self): - reference = BotContext.get_conversation_reference(ACTIVITY) + reference = TurnContext.get_conversation_reference(ACTIVITY) assert reference.activity_id == ACTIVITY.id assert reference.user == ACTIVITY.from_property @@ -219,8 +219,8 @@ def test_get_conversation_reference_should_return_valid_reference(self): assert reference.service_url == ACTIVITY.service_url def test_apply_conversation_reference_should_return_prepare_reply_when_is_incoming_is_False(self): - reference = BotContext.get_conversation_reference(ACTIVITY) - reply = BotContext.apply_conversation_reference(Activity(type='message', text='reply'), reference) + reference = TurnContext.get_conversation_reference(ACTIVITY) + reply = TurnContext.apply_conversation_reference(Activity(type='message', text='reply'), reference) assert reply.recipient == ACTIVITY.from_property assert reply.from_property == ACTIVITY.recipient @@ -229,8 +229,8 @@ def test_apply_conversation_reference_should_return_prepare_reply_when_is_incomi assert reply.channel_id == ACTIVITY.channel_id def test_apply_conversation_reference_when_is_incoming_is_True_should_not_prepare_a_reply(self): - reference = BotContext.get_conversation_reference(ACTIVITY) - reply = BotContext.apply_conversation_reference(Activity(type='message', text='reply'), reference, True) + reference = TurnContext.get_conversation_reference(ACTIVITY) + reply = TurnContext.apply_conversation_reference(Activity(type='message', text='reply'), reference, True) assert reply.recipient == ACTIVITY.recipient assert reply.from_property == ACTIVITY.from_property diff --git a/libraries/botbuilder-core/tests/test_user_state.py b/libraries/botbuilder-core/tests/test_user_state.py index d1c78aafe..335bced2b 100644 --- a/libraries/botbuilder-core/tests/test_user_state.py +++ b/libraries/botbuilder-core/tests/test_user_state.py @@ -3,7 +3,7 @@ import pytest -from botbuilder.core import BotContext, MemoryStorage, StoreItem, TestAdapter, UserState +from botbuilder.core import TurnContext, MemoryStorage, StoreItem, TestAdapter, UserState from botbuilder.schema import Activity, ChannelAccount RECEIVED_MESSAGE = Activity(type='message', @@ -21,7 +21,7 @@ class TestUserState: storage = MemoryStorage() adapter = TestAdapter() - context = BotContext(adapter, RECEIVED_MESSAGE) + context = TurnContext(adapter, RECEIVED_MESSAGE) middleware = UserState(storage) @pytest.mark.asyncio @@ -41,7 +41,7 @@ async def next_middleware(): @pytest.mark.asyncio async def test_should_reject_with_error_if_channel_id_is_missing(self): - context = BotContext(self.adapter, MISSING_CHANNEL_ID) + context = TurnContext(self.adapter, MISSING_CHANNEL_ID) async def next_middleware(): assert False, 'Should not have called next_middleware' @@ -55,7 +55,7 @@ async def next_middleware(): @pytest.mark.asyncio async def test_should_reject_with_error_if_from_property_is_missing(self): - context = BotContext(self.adapter, MISSING_FROM_PROPERTY) + context = TurnContext(self.adapter, MISSING_FROM_PROPERTY) async def next_middleware(): assert False, 'Should not have called next_middleware' diff --git a/samples/Console-EchoBot/adapter/console_adapter.py b/samples/Console-EchoBot/adapter/console_adapter.py index be28eca63..cda807d22 100644 --- a/samples/Console-EchoBot/adapter/console_adapter.py +++ b/samples/Console-EchoBot/adapter/console_adapter.py @@ -9,7 +9,7 @@ from botbuilder.schema import (Activity, ActivityTypes, ChannelAccount, ConversationAccount, ResourceResponse, ConversationReference) -from botbuilder.core.bot_context import BotContext +from botbuilder.core.turn_context import TurnContext from botbuilder.core.bot_adapter import BotAdapter @@ -81,11 +81,11 @@ async def process_activity(self, logic: Callable): timestamp=datetime.datetime.now(), id=str(self._next_id)) - activity = BotContext.apply_conversation_reference(activity, self.reference, True) - context = BotContext(self, activity) + activity = TurnContext.apply_conversation_reference(activity, self.reference, True) + context = TurnContext(self, activity) await self.run_middleware(context, logic) - async def send_activities(self, context: BotContext, activities: List[Activity]): + async def send_activities(self, context: TurnContext, activities: List[Activity]): """ Logs a series of activities to the console. :param context: @@ -124,9 +124,9 @@ async def next_activity(i: int): await next_activity(0) - async def delete_activity(self, context: BotContext, reference: ConversationReference): + async def delete_activity(self, context: TurnContext, reference: ConversationReference): """ - Not supported for the ConsoleAdapter. Calling this method or `BotContext.delete_activity()` + Not supported for the ConsoleAdapter. Calling this method or `TurnContext.delete_activity()` will result an error being returned. :param context: :param reference: @@ -134,9 +134,9 @@ async def delete_activity(self, context: BotContext, reference: ConversationRefe """ raise NotImplementedError('ConsoleAdapter.delete_activity(): not supported.') - async def update_activity(self, context: BotContext, activity: Activity): + async def update_activity(self, context: TurnContext, activity: Activity): """ - Not supported for the ConsoleAdapter. Calling this method or `BotContext.update_activity()` + Not supported for the ConsoleAdapter. Calling this method or `TurnContext.update_activity()` will result an error being returned. :param context: :param activity: diff --git a/samples/Console-EchoBot/main.py b/samples/Console-EchoBot/main.py index c7a954922..a970f55d9 100644 --- a/samples/Console-EchoBot/main.py +++ b/samples/Console-EchoBot/main.py @@ -2,7 +2,7 @@ # Licensed under the MIT License. import asyncio -from botbuilder.core import BotContext, ConversationState, UserState, MemoryStorage +from botbuilder.core import TurnContext, ConversationState, UserState, MemoryStorage from botbuilder.schema import ActivityTypes from adapter import ConsoleAdapter @@ -22,7 +22,7 @@ adapter.use(conversation_state) -async def logic(context: BotContext): +async def logic(context: TurnContext): if context.activity.type == ActivityTypes.message: state = await conversation_state.get(context) diff --git a/samples/EchoBot-with-State/main.py b/samples/EchoBot-with-State/main.py index bbcea4149..e966076cb 100644 --- a/samples/EchoBot-with-State/main.py +++ b/samples/EchoBot-with-State/main.py @@ -8,7 +8,7 @@ from aiohttp import web from botbuilder.schema import (Activity, ActivityTypes) -from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, BotContext, +from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, TurnContext, ConversationState, MemoryStorage, UserState) APP_ID = '' @@ -40,7 +40,7 @@ async def create_reply_activity(request_activity, text) -> Activity: service_url=request_activity.service_url) -async def handle_message(context: BotContext) -> web.Response: +async def handle_message(context: TurnContext) -> web.Response: # Access the state for the conversation between the user and the bot. state = await conversation_state.get(context) @@ -54,7 +54,7 @@ async def handle_message(context: BotContext) -> web.Response: return web.Response(status=202) -async def handle_conversation_update(context: BotContext) -> web.Response: +async def handle_conversation_update(context: TurnContext) -> web.Response: if context.activity.members_added[0].id != context.activity.recipient.id: response = await create_reply_activity(context.activity, 'Welcome to the Echo Adapter Bot!') await context.send_activity(response) @@ -65,7 +65,7 @@ async def unhandled_activity() -> web.Response: return web.Response(status=404) -async def request_handler(context: BotContext) -> web.Response: +async def request_handler(context: TurnContext) -> web.Response: if context.activity.type == 'message': return await handle_message(context) elif context.activity.type == 'conversationUpdate': diff --git a/samples/Rich-Cards-Bot/main.py b/samples/Rich-Cards-Bot/main.py index 953884bea..d8687bc7d 100644 --- a/samples/Rich-Cards-Bot/main.py +++ b/samples/Rich-Cards-Bot/main.py @@ -15,7 +15,7 @@ ThumbnailCard, VideoCard, ReceiptCard, SigninCard, Fact, ReceiptItem) -from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, BotContext, +from botbuilder.core import (BotFrameworkAdapter, BotFrameworkAdapterSettings, TurnContext, ConversationState, MemoryStorage, UserState, CardFactory) """Import AdaptiveCard content from adjacent file""" from adaptive_card_example import ADAPTIVE_CARD_CONTENT @@ -144,7 +144,7 @@ async def create_reply_activity(request_activity: Activity, text: str, attachmen return activity -async def handle_message(context: BotContext) -> web.Response: +async def handle_message(context: TurnContext) -> web.Response: # Access the state for the conversation between the user and the bot. state = await conversation_state.get(context) if hasattr(state, 'in_prompt'): @@ -181,7 +181,7 @@ async def handle_message(context: BotContext) -> web.Response: return web.Response(status=202) -async def card_response(context: BotContext) -> web.Response: +async def card_response(context: TurnContext) -> web.Response: response = context.activity.text.strip() choice_dict = { '1': [create_adaptive_card], 'adaptive card': [create_adaptive_card], @@ -214,7 +214,7 @@ async def card_response(context: BotContext) -> web.Response: return web.Response(status=200) -async def handle_conversation_update(context: BotContext) -> web.Response: +async def handle_conversation_update(context: TurnContext) -> web.Response: if context.activity.members_added[0].id != context.activity.recipient.id: response = await create_reply_activity(context.activity, 'Welcome to the Rich Cards Bot!') await context.send_activity(response) @@ -225,7 +225,7 @@ async def unhandled_activity() -> web.Response: return web.Response(status=404) -async def request_handler(context: BotContext) -> web.Response: +async def request_handler(context: TurnContext) -> web.Response: if context.activity.type == 'message': return await handle_message(context) elif context.activity.type == 'conversationUpdate':