Esempio n. 1
0
 def test_serialization(self):
     ctx = Context('foo', 5, parameters={'bar': 'baz'})
     expected = {
         'name': 'foo',
         'lifespanCount': 5,
         'parameters': {
             'bar': 'baz'
         }
     }
     assert ctx.to_json() == expected
Esempio n. 2
0
 def test_as_list_with_deleted_ctx(self):
     contexts = [
         Context('foo', lifespan_count=5),
         Context('bar', lifespan_count=5)
     ]
     ctx_manager = ContextManager(contexts)
     ctx_manager.delete('bar')
     as_list = ctx_manager.as_list()
     assert len(as_list) == 2
     assert as_list[0].lifespan_count == 5
     assert as_list[1].lifespan_count == 0
Esempio n. 3
0
 def test_iter(self):
     ctx = Context('foo', 5, parameters={'bar': 'baz'})
     ctx_iter = iter(ctx)
     assert isinstance(ctx_iter, Iterator)
     assert next(ctx_iter) == 'bar'
     with pytest.raises(StopIteration):
         _ = next(ctx_iter)
Esempio n. 4
0
 def test_delattr(self):
     ctx = Context('foo')
     ctx_manager = ContextManager([ctx])
     del ctx_manager.foo
     assert 'foo' not in ctx_manager
     with pytest.raises(AttributeError):
         del ctx_manager.bar
Esempio n. 5
0
 def test_collection_iter(self):
     ctx = Context('foo')
     ctx_manager = ContextManager([ctx])
     ctx_iter = iter(ctx_manager)
     assert isinstance(ctx_iter, Iterator)
     assert next(ctx_iter) == ctx
     with pytest.raises(StopIteration):
         next(ctx_iter)
Esempio n. 6
0
 def test_delete_keep_in_registry(self):
     ctx_manager = ContextManager([Context('foo')])
     ctx_manager._context_registry.register('foo', keep_around=True)
     assert ctx_manager._context_registry.should_keep_around('foo')
     ctx_manager.delete('foo', keep_in_registry=True)
     assert 'foo' not in ctx_manager
     assert 'foo' in ctx_manager._marked_for_deletion
     assert ctx_manager._context_registry.should_keep_around('foo')
Esempio n. 7
0
 def test_delete_dont_keep_in_registry(self):
     ctx_manager = ContextManager([Context('foo')])
     ctx_manager._context_registry.register('foo', keep_around=True)
     assert ctx_manager._context_registry.should_keep_around('foo')
     ctx_manager.delete('foo', keep_in_registry=False)
     assert 'foo' not in ctx_manager
     assert 'foo' in ctx_manager._marked_for_deletion
     with pytest.raises(ContextNotRegisteredError):
         assert ctx_manager._context_registry.should_keep_around('foo')
Esempio n. 8
0
 def _initialize_default_contexts(self,
                                  contexts: MutableSequence['Context'],
                                  session: str) -> None:
     """Initialize contexts that have a default but are not present."""
     present = set(ctx.display_name for ctx in contexts)
     missing = self._context_registry.have_default_factories() - present
     for name in missing:
         default_factory = self._context_registry.get_default_factory(name)
         parameters = default_factory()
         ctx_name = make_full_ctx_name(session, name)
         ctx = Context(ctx_name, parameters=parameters)
         contexts.append(ctx)
Esempio n. 9
0
    def __init__(
        self,
        webhook_request: Optional[_df.WebhookRequest] = None,
        context_manager: Optional['ContextManager'] = None,
        integration_convs: Optional[Mapping[
            str, AbstractIntegrationConversation]] = None,
    ) -> None:
        """Initialize a conversation.

        This is not supposed to be done by the user, several steps usually
        preceed the initialization to set the conversation up correctly.

        Args:
            webhook_request: The :class:`.WebhookRequest` that this
                conversation represents.
            context_manager: The :class:`.ContextManager` that handles the
                contexts.
            integration_convs: The mapping of integration conversations.
        """
        if webhook_request is None:
            odir = self._df.OriginalDetectIntentRequest()
            webhook_request = self._df.WebhookRequest(
                query_result=self._df.QueryResult(intent=self._df.Intent()),
                original_detect_intent_request=odir,
            )
        self._webhook_request = webhook_request
        self._contexts = context_manager or ContextManager(contexts=[
            Context('_session_context', parameters=SessionContext())
        ])
        self._integration_convs: DefaultDict[
            str, AbstractIntegrationConversation] = defaultdict(
                GenericIntegrationConversation)
        if integration_convs:
            self._integration_convs.update(integration_convs)

        self._session_ctx = self.contexts.get('_session_context').parameters
        self._webhook_response = self._df.WebhookResponse()

        if self.webhook_request.query_result.intent.is_fallback:
            self._session_ctx.fallback_level += 1
        else:
            self._session_ctx.fallback_level = 0
Esempio n. 10
0
 def _initialize_conversation(
         self, webhook_request: WebhookRequest) -> DialogflowConversation:
     """Initialize the conversation object from a WebhookRequest."""
     contexts = [
         Context.from_context(ctx)
         for ctx in webhook_request.query_result.output_contexts
     ]
     self._deserialize_context_params(contexts)
     self._initialize_default_contexts(contexts, webhook_request.session)
     self._reset_lifespan_of_keep_around_contexts(contexts)
     context_manager = ContextManager(
         contexts=contexts,
         session=webhook_request.session,
         context_registry=self._context_registry)
     integration_convs = self._integration_registry.init_integration_convs(
         webhook_request.original_detect_intent_request)
     return self._conv_cls(
         webhook_request,
         context_manager=context_manager,
         integration_convs=integration_convs,
     )
Esempio n. 11
0
 def test_get(self):
     ctx = Context('foo')
     ctx_manager = ContextManager([ctx])
     assert ctx_manager.get('foo') == ctx
Esempio n. 12
0
 def test_as_list(self):
     contexts = [Context('foo'), Context('bar')]
     ctx_manager = ContextManager(contexts)
     assert ctx_manager.as_list() == contexts
Esempio n. 13
0
 def test_delattr_to_ctx_param(self):
     ctx = Context('foo', parameters={'bar': 'baz'})
     ctx_manager = ContextManager([ctx])
     del ctx_manager.foo['bar']
     assert ctx.parameters == {}
Esempio n. 14
0
 def test_get_as_attribute(self):
     ctx = Context('foo')
     ctx_manager = ContextManager([ctx])
     assert ctx_manager.foo == ctx
Esempio n. 15
0
 def test_getattr_to_ctx_param(self):
     ctx = Context('foo', parameters={'bar': 'baz'})
     ctx_manager = ContextManager([ctx])
     assert ctx_manager.foo['bar'] == 'baz'
Esempio n. 16
0
 def test_set_with_invalid_display_name(self, ctx_manager):
     ctx = Context('föö', 5, parameters={'bar': 'baz'})
     with pytest.raises(ValueError):
         ctx_manager.set(ctx)
Esempio n. 17
0
 def test_delitem(self):
     ctx = Context('foo', 5, parameters={'bar': 'baz'})
     del ctx['bar']
     assert ctx.parameters == {}
Esempio n. 18
0
 def test_collection_contains(self):
     ctx_manager = ContextManager([Context('foo')])
     assert 'foo' in ctx_manager
     assert 'bar' not in ctx_manager
Esempio n. 19
0
 def test_set_with_ctx_instance_with_full_name(self, ctx_manager):
     ctx = Context(name='projects/bar/agent/sessions/baz/contexts/foo',
                   lifespan_count=5,
                   parameters={'bar': 'baz'})
     ctx_manager.set(ctx)
     assert ctx_manager.get('foo') == ctx
Esempio n. 20
0
 def test_has(self):
     ctx_manager = ContextManager([Context('foo')])
     assert ctx_manager.has('foo')
     assert not ctx_manager.has('bar')
Esempio n. 21
0
 def test_delete_as_attribute(self):
     ctx_manager = ContextManager([Context('foo')])
     del ctx_manager.foo
     assert 'foo' not in ctx_manager
     assert 'foo' in ctx_manager._marked_for_deletion
Esempio n. 22
0
 def test_set_with_ctx_instance_and_params(self, ctx_manager):
     ctx = Context('foo', 5, parameters={'bar': 'baz'})
     with pytest.raises(ValueError):
         ctx_manager.set(ctx, lifespan_count=5)
     with pytest.raises(ValueError):
         ctx_manager.set(ctx, bar='baz')
Esempio n. 23
0
 def test_deserialization(self):
     ctx = {'name': 'foo', 'lifespanCount': 5, 'parameters': {'bar': 'baz'}}
     expected = Context('foo', 5, parameters={'bar': 'baz'})
     assert Context.from_json(ctx) == expected
Esempio n. 24
0
 def test_set_with_ctx_instance(self, ctx_manager):
     ctx = Context('foo', 5, parameters={'bar': 'baz'})
     ctx_manager.set(ctx)
     assert ctx_manager.get('foo') == ctx
Esempio n. 25
0
 def test_setitem(self):
     ctx = Context('foo', 5, parameters={'bar': 'baz'})
     ctx['bar'] = 42
     assert ctx.parameters['bar'] == 42
Esempio n. 26
0
 def test_getattr(self):
     ctx = Context('foo')
     ctx_manager = ContextManager([ctx])
     assert ctx_manager.foo == ctx
     with pytest.raises(AttributeError):
         _ = ctx_manager.bar
Esempio n. 27
0
 def test_len(self):
     ctx = Context('foo', 5, parameters={'bar': 'baz'})
     assert len(ctx) == len(ctx.parameters)
Esempio n. 28
0
 def test_delete(self):
     ctx_manager = ContextManager([Context('foo')])
     ctx_manager.delete('foo')
     assert 'foo' not in ctx_manager
     assert 'foo' in ctx_manager._marked_for_deletion
Esempio n. 29
0
 def test_display_name(self, name, expected):
     assert Context(name).display_name == expected
Esempio n. 30
0
 def test_in_operator(self):
     ctx_manager = ContextManager([Context('foo')])
     assert 'foo' in ctx_manager
     assert 'bar ' not in ctx_manager