File size: 12,690 Bytes
0827183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# pylint: disable=pointless-string-statement

from enum import Enum
from typing import Callable, List, Tuple

import aiounittest

from botbuilder.core import (
    AutoSaveStateMiddleware,
    BotAdapter,
    ConversationState,
    MemoryStorage,
    MessageFactory,
    UserState,
    TurnContext,
)
from botbuilder.core.adapters import TestAdapter
from botbuilder.core.skills import SkillHandler, SkillConversationReference
from botbuilder.dialogs import (
    ComponentDialog,
    Dialog,
    DialogContext,
    DialogEvents,
    DialogInstance,
    DialogReason,
    TextPrompt,
    WaterfallDialog,
    DialogManager,
    DialogManagerResult,
    DialogTurnStatus,
    WaterfallStepContext,
)
from botbuilder.dialogs.prompts import PromptOptions
from botbuilder.schema import (
    Activity,
    ActivityTypes,
    ChannelAccount,
    ConversationAccount,
    EndOfConversationCodes,
    InputHints,
)
from botframework.connector.auth import AuthenticationConstants, ClaimsIdentity


class SkillFlowTestCase(str, Enum):
    # DialogManager is executing on a root bot with no skills (typical standalone bot).
    root_bot_only = "RootBotOnly"

    # DialogManager is executing on a root bot handling replies from a skill.
    root_bot_consuming_skill = "RootBotConsumingSkill"

    # DialogManager is executing in a skill that is called from a root and calling another skill.
    middle_skill = "MiddleSkill"

    # DialogManager is executing in a skill that is called from a parent (a root or another skill) but doesn"t call
    # another skill.
    leaf_skill = "LeafSkill"


class SimpleComponentDialog(ComponentDialog):
    # An App ID for a parent bot.
    parent_bot_id = "00000000-0000-0000-0000-0000000000PARENT"

    # An App ID for a skill bot.
    skill_bot_id = "00000000-0000-0000-0000-00000000000SKILL"

    # Captures an EndOfConversation if it was sent to help with assertions.
    eoc_sent: Activity = None

    # Property to capture the DialogManager turn results and do assertions.
    dm_turn_result: DialogManagerResult = None

    def __init__(
        self, id: str = None, prop: str = None
    ):  # pylint: disable=unused-argument
        super().__init__(id or "SimpleComponentDialog")
        self.text_prompt = "TextPrompt"
        self.waterfall_dialog = "WaterfallDialog"
        self.add_dialog(TextPrompt(self.text_prompt))
        self.add_dialog(
            WaterfallDialog(
                self.waterfall_dialog,
                [
                    self.prompt_for_name,
                    self.final_step,
                ],
            )
        )
        self.initial_dialog_id = self.waterfall_dialog
        self.end_reason = None

    @staticmethod
    async def create_test_flow(
        dialog: Dialog,
        test_case: SkillFlowTestCase = SkillFlowTestCase.root_bot_only,
        enabled_trace=False,
    ) -> TestAdapter:
        conversation_id = "testFlowConversationId"
        storage = MemoryStorage()
        conversation_state = ConversationState(storage)
        user_state = UserState(storage)

        activity = Activity(
            channel_id="test",
            service_url="https://test.com",
            from_property=ChannelAccount(id="user1", name="User1"),
            recipient=ChannelAccount(id="bot", name="Bot"),
            conversation=ConversationAccount(
                is_group=False, conversation_type=conversation_id, id=conversation_id
            ),
        )

        dialog_manager = DialogManager(dialog)
        dialog_manager.user_state = user_state
        dialog_manager.conversation_state = conversation_state

        async def logic(context: TurnContext):
            if test_case != SkillFlowTestCase.root_bot_only:
                # Create a skill ClaimsIdentity and put it in turn_state so isSkillClaim() returns True.
                claims_identity = ClaimsIdentity({}, False)
                claims_identity.claims["ver"] = (
                    "2.0"  # AuthenticationConstants.VersionClaim
                )
                claims_identity.claims["aud"] = (
                    SimpleComponentDialog.skill_bot_id
                )  # AuthenticationConstants.AudienceClaim
                claims_identity.claims["azp"] = (
                    SimpleComponentDialog.parent_bot_id
                )  # AuthenticationConstants.AuthorizedParty
                context.turn_state[BotAdapter.BOT_IDENTITY_KEY] = claims_identity

                if test_case == SkillFlowTestCase.root_bot_consuming_skill:
                    # Simulate the SkillConversationReference with a channel OAuthScope stored in turn_state.
                    # This emulates a response coming to a root bot through SkillHandler.
                    context.turn_state[
                        SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY
                    ] = SkillConversationReference(
                        None, AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE
                    )

                if test_case == SkillFlowTestCase.middle_skill:
                    # Simulate the SkillConversationReference with a parent Bot ID stored in turn_state.
                    # This emulates a response coming to a skill from another skill through SkillHandler.
                    context.turn_state[
                        SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY
                    ] = SkillConversationReference(
                        None, SimpleComponentDialog.parent_bot_id
                    )

            async def aux(
                turn_context: TurnContext,  # pylint: disable=unused-argument
                activities: List[Activity],
                next: Callable,
            ):
                for activity in activities:
                    if activity.type == ActivityTypes.end_of_conversation:
                        SimpleComponentDialog.eoc_sent = activity
                        break

                return await next()

            # Interceptor to capture the EoC activity if it was sent so we can assert it in the tests.
            context.on_send_activities(aux)

            SimpleComponentDialog.dm_turn_result = await dialog_manager.on_turn(context)

        adapter = TestAdapter(logic, activity, enabled_trace)
        adapter.use(AutoSaveStateMiddleware([user_state, conversation_state]))

        return adapter

    async def on_end_dialog(
        self, context: DialogContext, instance: DialogInstance, reason: DialogReason
    ):
        self.end_reason = reason
        return await super().on_end_dialog(context, instance, reason)

    async def prompt_for_name(self, step: WaterfallStepContext):
        return await step.prompt(
            self.text_prompt,
            PromptOptions(
                prompt=MessageFactory.text(
                    "Hello, what is your name?", None, InputHints.expecting_input
                ),
                retry_prompt=MessageFactory.text(
                    "Hello, what is your name again?", None, InputHints.expecting_input
                ),
            ),
        )

    async def final_step(self, step: WaterfallStepContext):
        await step.context.send_activity(f"Hello { step.result }, nice to meet you!")
        return await step.end_dialog(step.result)


class DialogManagerTests(aiounittest.AsyncTestCase):
    """
    self.beforeEach(() => {
        _dmTurnResult = undefined
    })
    """

    async def test_handles_bot_and_skills(self):
        construction_data: List[Tuple[SkillFlowTestCase, bool]] = [
            (SkillFlowTestCase.root_bot_only, False),
            (SkillFlowTestCase.root_bot_consuming_skill, False),
            (SkillFlowTestCase.middle_skill, True),
            (SkillFlowTestCase.leaf_skill, True),
        ]

        for test_case, should_send_eoc in construction_data:
            with self.subTest(test_case=test_case, should_send_eoc=should_send_eoc):
                SimpleComponentDialog.dm_turn_result = None
                SimpleComponentDialog.eoc_sent = None
                dialog = SimpleComponentDialog()
                test_flow = await SimpleComponentDialog.create_test_flow(
                    dialog, test_case
                )
                step1 = await test_flow.send("Hi")
                step2 = await step1.assert_reply("Hello, what is your name?")
                step3 = await step2.send("SomeName")
                await step3.assert_reply("Hello SomeName, nice to meet you!")

                self.assertEqual(
                    SimpleComponentDialog.dm_turn_result.turn_result.status,
                    DialogTurnStatus.Complete,
                )

                self.assertEqual(dialog.end_reason, DialogReason.EndCalled)
                if should_send_eoc:
                    self.assertTrue(
                        bool(SimpleComponentDialog.eoc_sent),
                        "Skills should send EndConversation to channel",
                    )
                    self.assertEqual(
                        SimpleComponentDialog.eoc_sent.type,
                        ActivityTypes.end_of_conversation,
                    )
                    self.assertEqual(
                        SimpleComponentDialog.eoc_sent.code,
                        EndOfConversationCodes.completed_successfully,
                    )
                    self.assertEqual(SimpleComponentDialog.eoc_sent.value, "SomeName")
                else:
                    self.assertIsNone(
                        SimpleComponentDialog.eoc_sent,
                        "Root bot should not send EndConversation to channel",
                    )

    async def test_skill_handles_eoc_from_parent(self):
        SimpleComponentDialog.dm_turn_result = None
        dialog = SimpleComponentDialog()
        test_flow = await SimpleComponentDialog.create_test_flow(
            dialog, SkillFlowTestCase.leaf_skill
        )

        step1 = await test_flow.send("Hi")
        step2 = await step1.assert_reply("Hello, what is your name?")
        await step2.send(Activity(type=ActivityTypes.end_of_conversation))

        self.assertEqual(
            SimpleComponentDialog.dm_turn_result.turn_result.status,
            DialogTurnStatus.Cancelled,
        )

    async def test_skill_handles_reprompt_from_parent(self):
        SimpleComponentDialog.dm_turn_result = None
        dialog = SimpleComponentDialog()
        test_flow = await SimpleComponentDialog.create_test_flow(
            dialog, SkillFlowTestCase.leaf_skill
        )

        step1 = await test_flow.send("Hi")
        step2 = await step1.assert_reply("Hello, what is your name?")
        step3 = await step2.send(
            Activity(type=ActivityTypes.event, name=DialogEvents.reprompt_dialog)
        )
        await step3.assert_reply("Hello, what is your name?")

        self.assertEqual(
            SimpleComponentDialog.dm_turn_result.turn_result.status,
            DialogTurnStatus.Waiting,
        )

    async def test_skill_should_return_empty_on_reprompt_with_no_dialog(self):
        SimpleComponentDialog.dm_turn_result = None
        dialog = SimpleComponentDialog()
        test_flow = await SimpleComponentDialog.create_test_flow(
            dialog, SkillFlowTestCase.leaf_skill
        )

        await test_flow.send(
            Activity(type=ActivityTypes.event, name=DialogEvents.reprompt_dialog)
        )

        self.assertEqual(
            SimpleComponentDialog.dm_turn_result.turn_result.status,
            DialogTurnStatus.Empty,
        )

    async def test_trace_bot_state(self):
        SimpleComponentDialog.dm_turn_result = None
        dialog = SimpleComponentDialog()

        def assert_is_trace(activity, description):  # pylint: disable=unused-argument
            assert activity.type == ActivityTypes.trace

        def assert_is_trace_and_label(activity, description):
            assert_is_trace(activity, description)
            assert activity.label == "Bot State"

        test_flow = await SimpleComponentDialog.create_test_flow(
            dialog, SkillFlowTestCase.root_bot_only, True
        )

        step1 = await test_flow.send("Hi")
        step2 = await step1.assert_reply("Hello, what is your name?")
        step3 = await step2.assert_reply(assert_is_trace_and_label)
        step4 = await step3.send("SomeName")
        step5 = await step4.assert_reply("Hello SomeName, nice to meet you!")
        await step5.assert_reply(assert_is_trace_and_label)

        self.assertEqual(
            SimpleComponentDialog.dm_turn_result.turn_result.status,
            DialogTurnStatus.Complete,
        )