File size: 7,940 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
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

from uuid import uuid4
from typing import Awaitable, Callable, Dict, Union


from unittest.mock import Mock
import aiounittest

from botbuilder.core import MessageFactory, InvokeResponse
from botbuilder.core.skills import (
    BotFrameworkSkill,
    ConversationIdFactoryBase,
    SkillConversationIdFactoryOptions,
    SkillConversationReference,
)
from botbuilder.integration.aiohttp.skills import SkillHttpClient
from botbuilder.schema import Activity, ConversationAccount, ConversationReference
from botframework.connector.auth import (
    AuthenticationConstants,
    ChannelProvider,
    GovernmentConstants,
)


class SimpleConversationIdFactory(ConversationIdFactoryBase):
    def __init__(self, conversation_id: str):
        self._conversation_id = conversation_id
        self._conversation_refs: Dict[str, SkillConversationReference] = {}
        # Public property to capture and assert the options passed to CreateSkillConversationIdAsync.
        self.creation_options: SkillConversationIdFactoryOptions = None

    async def create_skill_conversation_id(
        self,
        options_or_conversation_reference: Union[
            SkillConversationIdFactoryOptions, ConversationReference
        ],
    ) -> str:
        self.creation_options = options_or_conversation_reference

        key = self._conversation_id
        self._conversation_refs[key] = self._conversation_refs.get(
            key,
            SkillConversationReference(
                conversation_reference=options_or_conversation_reference.activity.get_conversation_reference(),
                oauth_scope=options_or_conversation_reference.from_bot_oauth_scope,
            ),
        )
        return key

    async def get_skill_conversation_reference(
        self, skill_conversation_id: str
    ) -> SkillConversationReference:
        return self._conversation_refs[skill_conversation_id]

    async def delete_conversation_reference(self, skill_conversation_id: str):
        raise NotImplementedError()


class TestSkillHttpClientTests(aiounittest.AsyncTestCase):
    async def test_post_activity_with_originating_audience(self):
        conversation_id = str(uuid4())
        conversation_id_factory = SimpleConversationIdFactory(conversation_id)
        test_activity = MessageFactory.text("some message")
        test_activity.conversation = ConversationAccount()
        skill = BotFrameworkSkill(
            id="SomeSkill",
            app_id="",
            skill_endpoint="https://someskill.com/api/messages",
        )

        async def _mock_post_content(
            to_url: str,
            token: str,  # pylint: disable=unused-argument
            activity: Activity,
        ) -> (int, object):
            nonlocal self
            self.assertEqual(skill.skill_endpoint, to_url)
            # Assert that the activity being sent has what we expect.
            self.assertEqual(conversation_id, activity.conversation.id)
            self.assertEqual("https://parentbot.com/api/messages", activity.service_url)

            # Create mock response.
            return 200, None

        sut = await self._create_http_client_with_mock_handler(
            _mock_post_content, conversation_id_factory
        )

        result = await sut.post_activity_to_skill(
            "",
            skill,
            "https://parentbot.com/api/messages",
            test_activity,
            "someOriginatingAudience",
        )

        # Assert factory options
        self.assertEqual("", conversation_id_factory.creation_options.from_bot_id)
        self.assertEqual(
            "someOriginatingAudience",
            conversation_id_factory.creation_options.from_bot_oauth_scope,
        )
        self.assertEqual(
            test_activity, conversation_id_factory.creation_options.activity
        )
        self.assertEqual(
            skill, conversation_id_factory.creation_options.bot_framework_skill
        )

        # Assert result
        self.assertIsInstance(result, InvokeResponse)
        self.assertEqual(200, result.status)

    async def test_post_activity_using_invoke_response(self):
        for is_gov in [True, False]:
            with self.subTest(is_government=is_gov):
                # pylint: disable=undefined-variable
                # pylint: disable=cell-var-from-loop
                conversation_id = str(uuid4())
                conversation_id_factory = SimpleConversationIdFactory(conversation_id)
                test_activity = MessageFactory.text("some message")
                test_activity.conversation = ConversationAccount()
                expected_oauth_scope = (
                    AuthenticationConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE
                )
                mock_channel_provider: ChannelProvider = Mock(spec=ChannelProvider)

                def is_government_mock():
                    nonlocal expected_oauth_scope
                    if is_government:
                        expected_oauth_scope = (
                            GovernmentConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE
                        )

                    return is_government

                mock_channel_provider.is_government = Mock(
                    side_effect=is_government_mock
                )

                skill = BotFrameworkSkill(
                    id="SomeSkill",
                    app_id="",
                    skill_endpoint="https://someskill.com/api/messages",
                )

                async def _mock_post_content(
                    to_url: str,
                    token: str,  # pylint: disable=unused-argument
                    activity: Activity,
                ) -> (int, object):
                    nonlocal self

                    self.assertEqual(skill.skill_endpoint, to_url)
                    # Assert that the activity being sent has what we expect.
                    self.assertEqual(conversation_id, activity.conversation.id)
                    self.assertEqual(
                        "https://parentbot.com/api/messages", activity.service_url
                    )

                    # Create mock response.
                    return 200, None

                sut = await self._create_http_client_with_mock_handler(
                    _mock_post_content, conversation_id_factory
                )
                result = await sut.post_activity_to_skill(
                    "", skill, "https://parentbot.com/api/messages", test_activity
                )

                # Assert factory options
                self.assertEqual(
                    "", conversation_id_factory.creation_options.from_bot_id
                )
                self.assertEqual(
                    expected_oauth_scope,
                    conversation_id_factory.creation_options.from_bot_oauth_scope,
                )
                self.assertEqual(
                    test_activity, conversation_id_factory.creation_options.activity
                )
                self.assertEqual(
                    skill, conversation_id_factory.creation_options.bot_framework_skill
                )

                # Assert result
                self.assertIsInstance(result, InvokeResponse)
                self.assertEqual(200, result.status)

    # Helper to create an HttpClient with a mock message handler that executes function argument to validate the request
    # and mock a response.
    async def _create_http_client_with_mock_handler(
        self,
        value_function: Callable[[object], Awaitable[object]],
        id_factory: ConversationIdFactoryBase,
        channel_provider: ChannelProvider = None,
    ) -> SkillHttpClient:
        # pylint: disable=protected-access
        client = SkillHttpClient(Mock(), id_factory, channel_provider)
        client._post_content = value_function

        return client