repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
sequencelengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
encode/django-rest-framework
9,327
encode__django-rest-framework-9327
[ "9306" ]
0e4ed816279a8b9332544192ad90f7324f49cd62
diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -4,8 +4,6 @@ We don't bind behaviour to http method handlers yet, which allows mixin classes to be composed in interesting ways. """ -from django.db.models.query import prefetch_related_objects - from rest_framework import status from rest_framework.response import Response from rest_framework.settings import api_settings @@ -69,13 +67,10 @@ def update(self, request, *args, **kwargs): serializer.is_valid(raise_exception=True) self.perform_update(serializer) - queryset = self.filter_queryset(self.get_queryset()) - if queryset._prefetch_related_lookups: + if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to - # forcibly invalidate the prefetch cache on the instance, - # and then re-prefetch related objects + # forcibly invalidate the prefetch cache on the instance. instance._prefetched_objects_cache = {} - prefetch_related_objects([instance], *queryset._prefetch_related_lookups) return Response(serializer.data)
diff --git a/tests/test_prefetch_related.py b/tests/test_prefetch_related.py --- a/tests/test_prefetch_related.py +++ b/tests/test_prefetch_related.py @@ -1,5 +1,4 @@ from django.contrib.auth.models import Group, User -from django.db.models.query import Prefetch from django.test import TestCase from rest_framework import generics, serializers @@ -9,84 +8,51 @@ class UserSerializer(serializers.ModelSerializer): - permissions = serializers.SerializerMethodField() - - def get_permissions(self, obj): - ret = [] - for g in obj.groups.all(): - ret.extend([p.pk for p in g.permissions.all()]) - return ret - class Meta: model = User - fields = ('id', 'username', 'email', 'groups', 'permissions') - - -class UserRetrieveUpdate(generics.RetrieveUpdateAPIView): - queryset = User.objects.exclude(username='exclude').prefetch_related( - Prefetch('groups', queryset=Group.objects.exclude(name='exclude')), - 'groups__permissions', - ) - serializer_class = UserSerializer + fields = ('id', 'username', 'email', 'groups') -class UserUpdateWithoutPrefetchRelated(generics.UpdateAPIView): - queryset = User.objects.exclude(username='exclude') +class UserUpdate(generics.UpdateAPIView): + queryset = User.objects.exclude(username='exclude').prefetch_related('groups') serializer_class = UserSerializer class TestPrefetchRelatedUpdates(TestCase): def setUp(self): self.user = User.objects.create(username='tom', email='[email protected]') - self.groups = [Group.objects.create(name=f'group {i}') for i in range(10)] + self.groups = [Group.objects.create(name='a'), Group.objects.create(name='b')] self.user.groups.set(self.groups) - self.user.groups.add(Group.objects.create(name='exclude')) - self.expected = { - 'id': self.user.pk, - 'username': 'tom', - 'groups': [group.pk for group in self.groups], - 'email': '[email protected]', - 'permissions': [], - } - self.view = UserRetrieveUpdate.as_view() def test_prefetch_related_updates(self): - self.groups.append(Group.objects.create(name='c')) - request = factory.put( - '/', {'username': 'new', 'groups': [group.pk for group in self.groups]}, format='json' - ) - self.expected['username'] = 'new' - self.expected['groups'] = [group.pk for group in self.groups] - response = self.view(request, pk=self.user.pk) - assert User.objects.get(pk=self.user.pk).groups.count() == 12 - assert response.data == self.expected - # Update and fetch should get same result - request = factory.get('/') - response = self.view(request, pk=self.user.pk) - assert response.data == self.expected + view = UserUpdate.as_view() + pk = self.user.pk + groups_pk = self.groups[0].pk + request = factory.put('/', {'username': 'new', 'groups': [groups_pk]}, format='json') + response = view(request, pk=pk) + assert User.objects.get(pk=pk).groups.count() == 1 + expected = { + 'id': pk, + 'username': 'new', + 'groups': [1], + 'email': '[email protected]' + } + assert response.data == expected def test_prefetch_related_excluding_instance_from_original_queryset(self): """ Regression test for https://github.com/encode/django-rest-framework/issues/4661 """ - request = factory.put( - '/', {'username': 'exclude', 'groups': [self.groups[0].pk]}, format='json' - ) - response = self.view(request, pk=self.user.pk) - assert User.objects.get(pk=self.user.pk).groups.count() == 2 - self.expected['username'] = 'exclude' - self.expected['groups'] = [self.groups[0].pk] - assert response.data == self.expected - - def test_db_query_count(self): - request = factory.put( - '/', {'username': 'new'}, format='json' - ) - with self.assertNumQueries(7): - self.view(request, pk=self.user.pk) - - request = factory.put( - '/', {'username': 'new2'}, format='json' - ) - with self.assertNumQueries(16): - UserUpdateWithoutPrefetchRelated.as_view()(request, pk=self.user.pk) + view = UserUpdate.as_view() + pk = self.user.pk + groups_pk = self.groups[0].pk + request = factory.put('/', {'username': 'exclude', 'groups': [groups_pk]}, format='json') + response = view(request, pk=pk) + assert User.objects.get(pk=pk).groups.count() == 1 + expected = { + 'id': pk, + 'username': 'exclude', + 'groups': [1], + 'email': '[email protected]' + } + assert response.data == expected
3.15 not backwards compatible with 3.14 - "View' should either include a `queryset` attribute, or override the `get_queryset()` method." In 3.14, if a view was not a list view, and it overrode the `get_object` method, the view did not have to specify the `queryset` attribute or override the `get_queryset()` method. In these cases, the queryset is not needed or used. However, in 3.15 an AssertionError is now thrown in this case. Was this intentional? This appears to be related to the following call in the UpdateModelMixin which was recently added: `queryset = self.filter_queryset(self.get_queryset())` Upgrading to 3.15 introduces a breaking change that could be missed by many, especially as I see no reference to it in the release notes.
We just ran into this too. Also interested to know if it was intentional - I feel like this has got to be a pretty common pattern? Related PR: https://github.com/encode/django-rest-framework/pull/8043 I worked around it for now by just adding `ModelClass.objects.none()` to affected view classes, e.g.: ```diff class MeView(generics.RetrieveUpdateAPIView): + queryset = User.objects.none() serializer_class = MeSerializer def get_object(self): return self.request.user ``` Same here What is your `get_object()` method looking like? I started to look at a potential fix (https://github.com/encode/django-rest-framework/pull/9314) but after opening the pull request I noticed that I made a pretty significant assumption, that the `get_object` method isn't doing any prefetches. > What is your `get_object()` method looking like? I started to look at a potential fix (#9314) but after opening the pull request I noticed that I made a pretty significant assumption, that the `get_object` method isn't doing any prefetches. It is sometimes as simple as `return request.user` or potentially doing a `get_or_create` or a query on a queryset with many filters/select_related/prefetch_related/etc - there isn't one set pattern I have here. I don't totally understand the rationale behind clearing and refetching the related objects, but perhaps it is something that is just documented as the best practice, but does not throw an error if the queryset property or get_queryset method is not defined? In the end, I already updated all of the relevant code to define the queryset on my views, but the nature of the breaking change is concerning for others using the library. > In the end, I already updated all of the relevant code to define the queryset on my views, but the nature of the breaking change is concerning for others using the library. So if I read that correctly, the error message is not really an issue anymore, but your concern is more around the fact that it was a breaking change despite the major digit of DRF not having changed? Would adding this to the release note be enough to close this issue? While I agree that it didn't really follow [the advertised deprecation policy](https://www.django-rest-framework.org/community/release-notes/#deprecation-policy), in the case of the 3.15 release, it was a long time coming, and having 1.5 years separating it with the previous release was bound to contain unintended breaking changes... The fix I suggest would work in simple case, but would still require you to override the queryset in case of prefetches, and it's probably OK. In more complex cases, the error message tells exactly what is wrong, and user can easily fix it. I guess my concern is largely with the fact that it didn't follow the deprecation policy, but also with the change itself. Our code base is pretty extensively tested, but we generally do not go out of our way to test the core functionality in the libraries we use. The fact that there was this breaking change when there was, according to the policy, not supposed to be any, now has me concerned about other changes that might break something in our API that are not as obvious. Perhaps having more, smaller, releases could help mitigate some of these issues too. As you say, bundling over a year's worth of updates at once makes for a lot of potential places for issues to arise. When it comes to the specific change, there are many cases where it doesn't necessarily even make sense to specify the queryset, the most obvious one being when the result of `get_object` is the user on the request, but of course there are many others. There may be cases where `get_object` is not even returning a django model object, but maybe a dict or some other type. Forcing the queryset to be defined in some of these cases just seems unintuitive. I am obviously not as familiar with the overall code in the library, so I won't argue what should or should not be done, but it seems like some of the use cases were potentially overlooked, and while defining the queryset might be the optimal solution, making it required in these cases seems perhaps unncessary. > So if I read that correctly, the error message is not really an issue anymore, For those who happen to have "fixed" their downstream code. It is still a DRF regression. > but your concern is more around the fact that it was a breaking change despite the major digit of DRF not having changed? Would adding this to the release note be enough to close this issue? Not at all! A patch release with a fix in DRF is required, or alternatively the release should be withdrawn and re-released with a major version bump. > While I agree that it didn't really follow [the advertised deprecation policy](https://www.django-rest-framework.org/community/release-notes/#deprecation-policy), in the case of the 3.15 release, it was a long time coming, and having 1.5 years separating it with the previous release was bound to contain unintended breaking changes... That's a really concerning statement. Mature software with few releases generally is extraordinarily stable, not extraordinarily unstable. There's another regression caught by our application-side tests. I haven't had time to report it, but am planning to do so later this week. In my view, this is a symptom of a larger issue, as it suggests that DRF has insufficient test coverage. > The fix I suggest would work in simple case, but would still require you to override the queryset in case of prefetches, and it's probably OK. In more complex cases, the error message tells exactly what is wrong, and user can easily fix it. The code should simply gracefully handle (the exception in) scenarios where the queryset isn't defined or not of the expected type. > > So if I read that correctly, the error message is not really an issue anymore, > > For those who happen to have "fixed" their downstream code. It is still a DRF regression. > > > but your concern is more around the fact that it was a breaking change despite the major digit of DRF not having changed? Would adding this to the release note be enough to close this issue? > > Not at all! A patch release with a fix in DRF is required, or alternatively the release should be withdrawn and re-released with a major version bump. Definitely agreed here - this is a regression and should be addressed. > While I agree that it didn't really follow [the advertised deprecation policy](https://www.django-rest-framework.org/community/release-notes/#deprecation-policy), in the case of the 3.15 release, it was a long time coming, and having 1.5 years separating it with the previous release was bound to contain unintended breaking changes... How can there be unintended breaking changes in a point release? This is extremely concerning. >> While I agree that it didn't really follow [the advertised deprecation policy](https://www.django-rest-framework.org/community/release-notes/#deprecation-policy), in the case of the 3.15 release, it was a long time coming, and having 1.5 years separating it with the previous release was bound to contain unintended breaking changes... > > That's a really concerning statement. Mature software with few releases generally is extraordinarily stable, not extraordinarily unstable. So... I'm in complete agreement here. We've got two different aspects to be addressed here... * Releasing a 3.15.1 version, with appropriate fixes in place. * Ensuring that we make the project PR policy really clear, and [ensure that REST framework *isn't* accepting further changes other than security related fixes and changes required by newer Django versions](https://github.com/encode/django-rest-framework/discussions/9270#discussioncomment-8828323). > > > While I agree that it didn't really follow [the advertised deprecation policy](https://www.django-rest-framework.org/community/release-notes/#deprecation-policy), in the case of the 3.15 release, it was a long time coming, and having 1.5 years separating it with the previous release was bound to contain unintended breaking changes... > > > > > > That's a really concerning statement. Mature software with few releases generally is extraordinarily stable, not extraordinarily unstable. > > So... I'm in complete agreement here. > > We've got two different aspects to be addressed here... > > * Releasing a 3.15.1 version, with appropriate fixes in place. > * Ensuring that we make the project PR policy really clear, and [ensure that REST framework _isn't_ accepting further changes other than security related fixes and changes required by newer Django versions](https://github.com/encode/django-rest-framework/discussions/9270#discussioncomment-8828323). This is good to hear. My biggest concern was not that I had to update my code with a new release, its that this was a point release that should not have required me to do so. I am most concerned about what other updates were made that may cause issues that are not as immediately obvious, and it seems like there are at least a few others looking at the issue list. The whole situation has left me less confident in future DRF releases and considering rolling back to 3.14 as I know that it is stable and have much higher confidence in it behaving as I expect.
2024-03-21T16:15:39
encode/django-rest-framework
9,330
encode__django-rest-framework-9330
[ "9295" ]
0e4ed816279a8b9332544192ad90f7324f49cd62
diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py --- a/rest_framework/exceptions.py +++ b/rest_framework/exceptions.py @@ -144,30 +144,17 @@ class ValidationError(APIException): status_code = status.HTTP_400_BAD_REQUEST default_detail = _('Invalid input.') default_code = 'invalid' - default_params = {} - def __init__(self, detail=None, code=None, params=None): + def __init__(self, detail=None, code=None): if detail is None: detail = self.default_detail if code is None: code = self.default_code - if params is None: - params = self.default_params # For validation failures, we may collect many errors together, # so the details should always be coerced to a list if not already. - if isinstance(detail, str): - detail = [detail % params] - elif isinstance(detail, ValidationError): - detail = detail.detail - elif isinstance(detail, (list, tuple)): - final_detail = [] - for detail_item in detail: - if isinstance(detail_item, ValidationError): - final_detail += detail_item.detail - else: - final_detail += [detail_item % params if isinstance(detail_item, str) else detail_item] - detail = final_detail + if isinstance(detail, tuple): + detail = list(detail) elif not isinstance(detail, dict) and not isinstance(detail, list): detail = [detail]
diff --git a/tests/test_validation_error.py b/tests/test_validation_error.py --- a/tests/test_validation_error.py +++ b/tests/test_validation_error.py @@ -109,89 +109,3 @@ def test_validation_error_details(self): assert len(error.detail) == 2 assert str(error.detail[0]) == 'message1' assert str(error.detail[1]) == 'message2' - - -class TestValidationErrorWithDjangoStyle(TestCase): - def test_validation_error_details(self): - error = ValidationError('Invalid value: %(value)s', params={'value': '42'}) - assert str(error.detail[0]) == 'Invalid value: 42' - - def test_validation_error_details_tuple(self): - error = ValidationError( - detail=('Invalid value: %(value1)s', 'Invalid value: %(value2)s'), - params={'value1': '42', 'value2': '43'}, - ) - assert isinstance(error.detail, list) - assert len(error.detail) == 2 - assert str(error.detail[0]) == 'Invalid value: 42' - assert str(error.detail[1]) == 'Invalid value: 43' - - def test_validation_error_details_list(self): - error = ValidationError( - detail=['Invalid value: %(value1)s', 'Invalid value: %(value2)s', ], - params={'value1': '42', 'value2': '43'} - ) - assert isinstance(error.detail, list) - assert len(error.detail) == 2 - assert str(error.detail[0]) == 'Invalid value: 42' - assert str(error.detail[1]) == 'Invalid value: 43' - - def test_validation_error_details_validation_errors(self): - error = ValidationError( - detail=ValidationError( - detail='Invalid value: %(value1)s', - params={'value1': '42'}, - ), - ) - assert isinstance(error.detail, list) - assert len(error.detail) == 1 - assert str(error.detail[0]) == 'Invalid value: 42' - - def test_validation_error_details_validation_errors_list(self): - error = ValidationError( - detail=[ - ValidationError( - detail='Invalid value: %(value1)s', - params={'value1': '42'}, - ), - ValidationError( - detail='Invalid value: %(value2)s', - params={'value2': '43'}, - ), - 'Invalid value: %(value3)s' - ], - params={'value3': '44'} - ) - assert isinstance(error.detail, list) - assert len(error.detail) == 3 - assert str(error.detail[0]) == 'Invalid value: 42' - assert str(error.detail[1]) == 'Invalid value: 43' - assert str(error.detail[2]) == 'Invalid value: 44' - - def test_validation_error_details_validation_errors_nested_list(self): - error = ValidationError( - detail=[ - ValidationError( - detail='Invalid value: %(value1)s', - params={'value1': '42'}, - ), - ValidationError( - detail=[ - 'Invalid value: %(value2)s', - ValidationError( - detail='Invalid value: %(value3)s', - params={'value3': '44'}, - ) - ], - params={'value2': '43'}, - ), - 'Invalid value: %(value4)s' - ], - params={'value4': '45'} - ) - assert isinstance(error.detail, list) - assert len(error.detail) == 4 - assert str(error.detail[0]) == 'Invalid value: 42' - assert str(error.detail[1]) == 'Invalid value: 43' - assert str(error.detail[2]) == 'Invalid value: 44' - assert str(error.detail[3]) == 'Invalid value: 45'
3.15.0 - bug in rendering `%` characters from `ValidationError` The new `3.15.0` release introduced a bug in rendering errors from the `ValidationError` exception class. Given a serializer: ```python class MySerializer(Serializer): departure_datetime = serializers.DateTimeField( required=True, format="%Y-%m-%d %H:%M:%S", error_messages={"invalid": "Expects format %Y-%m-%d %H:%M:%S"}, ) ``` Calling `ValidationError` would raise the exception: ``` File "/.../.venv/lib/python3.11/site-packages/rest_framework/fields.py", line 603, in fail raise ValidationError(message_string, code=key) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../.venv/lib/python3.11/site-packages/rest_framework/exceptions.py", line 160, in __init__ detail = [detail % params] ~~~~~~~^~~~~~~~ ValueError: unsupported format character 'Y' (0x59) at index 27 ``` As expected, this can easily be reproduced in the console: ```python >>> ValidationError("Expects format %Y-%m-%d %H:%M:%S") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/.../.venv/lib/python3.11/site-packages/rest_framework/exceptions.py", line 160, in __init__ detail = [detail % params] ~~~~~~~^~~~~~~~ ValueError: unsupported format character 'Y' (0x59) at index 16 ``` or ```python >>> ["Expects format %Y-%m-%d %H:%M:%S" % {}] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: unsupported format character 'Y' (0x59) at index 16 ``` A solution would be to escape with double `%` characters any occurrence of `%` in the error messages. ```python class MySerializer(Serializer): departure_datetime = serializers.DateTimeField( required=True, format="%Y-%m-%d %H:%M:%S", error_messages={"invalid": "Expects format %%Y-%%m-%%d %%H:%%M:%%S"}, ) ``` Unsure this is a choice by design or not, as this wouldn't be the case on `3.14.x`?
This is coming from https://github.com/encode/django-rest-framework/pull/8863, which is very difficult to live with. The original motivation of that, from https://github.com/encode/django-rest-framework/issues/8077, had a reason of using more standard Django / python exception argument. But if you look at the Django error behavior: ```python from django.core.exceptions import ValidationError as dValidationError dValidationError("Expects format %Y-%m-%d %H:%M:%S") dValidationError("Expects format %Y-%m-%d %H:%M:%S").error_list ``` It does no similar formatting when given such a string. related fix https://github.com/encode/django-rest-framework/pull/9313
2024-03-21T22:18:45
encode/django-rest-framework
9,332
encode__django-rest-framework-9332
[ "9299" ]
a4d58077a0aca89b82f63ab33ebb36b16bf26d4a
diff --git a/rest_framework/permissions.py b/rest_framework/permissions.py --- a/rest_framework/permissions.py +++ b/rest_framework/permissions.py @@ -186,9 +186,9 @@ class DjangoModelPermissions(BasePermission): # Override this if you need to also provide 'view' permissions, # or if you want to provide custom permission codes. perms_map = { - 'GET': ['%(app_label)s.view_%(model_name)s'], + 'GET': [], 'OPTIONS': [], - 'HEAD': ['%(app_label)s.view_%(model_name)s'], + 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], @@ -239,13 +239,8 @@ def has_permission(self, request, view): queryset = self._queryset(view) perms = self.get_required_permissions(request.method, queryset.model) - change_perm = self.get_required_permissions('PUT', queryset.model) - - user = request.user - if request.method == 'GET': - return user.has_perms(perms) or user.has_perms(change_perm) - return user.has_perms(perms) + return request.user.has_perms(perms) class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions):
diff --git a/tests/test_permissions.py b/tests/test_permissions.py --- a/tests/test_permissions.py +++ b/tests/test_permissions.py @@ -80,8 +80,7 @@ def setUp(self): user.user_permissions.set([ Permission.objects.get(codename='add_basicmodel'), Permission.objects.get(codename='change_basicmodel'), - Permission.objects.get(codename='delete_basicmodel'), - Permission.objects.get(codename='view_basicmodel') + Permission.objects.get(codename='delete_basicmodel') ]) user = User.objects.create_user('updateonly', '[email protected]', 'password') @@ -140,15 +139,6 @@ def test_get_queryset_has_create_permissions(self): response = get_queryset_list_view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_201_CREATED) - def test_has_get_permissions(self): - request = factory.get('/', HTTP_AUTHORIZATION=self.permitted_credentials) - response = root_view(request) - self.assertEqual(response.status_code, status.HTTP_200_OK) - - request = factory.get('/1', HTTP_AUTHORIZATION=self.updateonly_credentials) - response = root_view(request, pk=1) - self.assertEqual(response.status_code, status.HTTP_200_OK) - def test_has_put_permissions(self): request = factory.put('/1', {'text': 'foobar'}, format='json', HTTP_AUTHORIZATION=self.permitted_credentials) @@ -166,15 +156,6 @@ def test_does_not_have_create_permissions(self): response = root_view(request, pk=1) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) - def test_does_not_have_get_permissions(self): - request = factory.get('/', HTTP_AUTHORIZATION=self.disallowed_credentials) - response = root_view(request) - self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) - - request = factory.get('/1', HTTP_AUTHORIZATION=self.disallowed_credentials) - response = root_view(request, pk=1) - self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) - def test_does_not_have_put_permissions(self): request = factory.put('/1', {'text': 'foobar'}, format='json', HTTP_AUTHORIZATION=self.disallowed_credentials)
`permissions.DjangoModelPermissionsOrAnonReadOnly` doesn't actually enable anonymous read-only access in 3.15 ### Discussed in https://github.com/encode/django-rest-framework/discussions/9298 <div type='discussions-op-text'> <sup>Originally posted by **lpomfrey** March 18, 2024</sup> As the title states, it seems from DRF 3.15 the `permissions.DjangoModelPermissionsOrAnonReadOnly` doesn't actually allow anonymous read only access as it inherits the check for the view permission on the model from `permissions.DjangoModelPermissions` class. It would seem to replicate the older behaviour `DjangoModelPermissionsOrAnonReadOnly` should set `'GET'` and `'HEAD'` in the `perms_map` to `[]` (along with setting `authenticated_users_only = False`). I'm not sure if this is by design and the recommended solution is to compose a set of permissions like `permissions.DjangoModelPermissions | ReadOnly` (providing a custom `ReadOnly` class), but the documentation still suggests it should work as it did in 3.14 and before.</div>
Confirmed. I thought I was going crazy. So... I think we should reassess and probably revert #8009, at least for a 3.15.1 release. (?) Requiring "view" permissions is a decent idea, but it unavoidably changes an existing behaviour in a way that's going to break some existing installations. Given that our permissions system was introduced before Django included the model "view" permission (I think?) it's not obvious that there's really a good way forward other than documenting what our built-in permissions do, and describing how to change them if needed. (Eg. how to require "view" permissions.) Is this the most sensible course of action on this one? If we were ignoring existing installations, it kind of feels like the plain `DjangoModelPermissions` _should_ handle the "view" permission. Although that then raises the question of what `DjangoModelPermissionsOrAnonReadOnly` should do in the case of a logged in user that _doesn't_ have the "view" permission, I'm not sure there's a common use case where you'd want an anonymous user to have more privileges than an authenticated one, but it could at first glance be expected to work either way. So, yes, ignoring the "view" permission and documenting that is probably the most sensible route, at least in the short-term.
2024-03-21T22:37:34
encode/django-rest-framework
9,333
encode__django-rest-framework-9333
[ "9310" ]
4f10c4e43ee57f4a2e387e0c8d44d28d21a3621c
diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py --- a/rest_framework/metadata.py +++ b/rest_framework/metadata.py @@ -11,7 +11,6 @@ from django.utils.encoding import force_str from rest_framework import exceptions, serializers -from rest_framework.fields import empty from rest_framework.request import clone_request from rest_framework.utils.field_mapping import ClassLookupDict @@ -150,7 +149,4 @@ def get_field_info(self, field): for choice_value, choice_name in field.choices.items() ] - if getattr(field, 'default', None) and field.default != empty and not callable(field.default): - field_info['default'] = field.default - return field_info diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -9,7 +9,6 @@ from django.utils.text import capfirst from rest_framework.compat import postgres_fields -from rest_framework.fields import empty from rest_framework.validators import UniqueValidator NUMERIC_FIELD_TYPES = ( @@ -128,9 +127,6 @@ def get_field_kwargs(field_name, model_field): kwargs['read_only'] = True return kwargs - if model_field.default is not None and model_field.default != empty and not callable(model_field.default): - kwargs['default'] = model_field.default - if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False
diff --git a/tests/test_metadata.py b/tests/test_metadata.py --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -184,135 +184,6 @@ def get_serializer(self): assert response.status_code == status.HTTP_200_OK assert response.data == expected - def test_actions_with_default(self): - """ - On generic views OPTIONS should return an 'actions' key with metadata - on the fields with default that may be supplied to PUT and POST requests. - """ - class NestedField(serializers.Serializer): - a = serializers.IntegerField(default=2) - b = serializers.IntegerField() - - class ExampleSerializer(serializers.Serializer): - choice_field = serializers.ChoiceField(['red', 'green', 'blue'], default='red') - integer_field = serializers.IntegerField( - min_value=1, max_value=1000, default=1 - ) - char_field = serializers.CharField( - min_length=3, max_length=40, default="example" - ) - list_field = serializers.ListField( - child=serializers.ListField( - child=serializers.IntegerField(default=1) - ) - ) - nested_field = NestedField() - uuid_field = serializers.UUIDField(label="UUID field") - - class ExampleView(views.APIView): - """Example view.""" - def post(self, request): - pass - - def get_serializer(self): - return ExampleSerializer() - - view = ExampleView.as_view() - response = view(request=request) - expected = { - 'name': 'Example', - 'description': 'Example view.', - 'renders': [ - 'application/json', - 'text/html' - ], - 'parses': [ - 'application/json', - 'application/x-www-form-urlencoded', - 'multipart/form-data' - ], - 'actions': { - 'POST': { - 'choice_field': { - 'type': 'choice', - 'required': False, - 'read_only': False, - 'label': 'Choice field', - "choices": [ - {'value': 'red', 'display_name': 'red'}, - {'value': 'green', 'display_name': 'green'}, - {'value': 'blue', 'display_name': 'blue'} - ], - 'default': 'red' - }, - 'integer_field': { - 'type': 'integer', - 'required': False, - 'read_only': False, - 'label': 'Integer field', - 'min_value': 1, - 'max_value': 1000, - 'default': 1 - }, - 'char_field': { - 'type': 'string', - 'required': False, - 'read_only': False, - 'label': 'Char field', - 'min_length': 3, - 'max_length': 40, - 'default': 'example' - }, - 'list_field': { - 'type': 'list', - 'required': True, - 'read_only': False, - 'label': 'List field', - 'child': { - 'type': 'list', - 'required': True, - 'read_only': False, - 'child': { - 'type': 'integer', - 'required': False, - 'read_only': False, - 'default': 1 - } - } - }, - 'nested_field': { - 'type': 'nested object', - 'required': True, - 'read_only': False, - 'label': 'Nested field', - 'children': { - 'a': { - 'type': 'integer', - 'required': False, - 'read_only': False, - 'label': 'A', - 'default': 2 - }, - 'b': { - 'type': 'integer', - 'required': True, - 'read_only': False, - 'label': 'B' - } - } - }, - 'uuid_field': { - 'type': 'string', - 'required': True, - 'read_only': False, - 'label': 'UUID field' - } - } - } - } - assert response.status_code == status.HTTP_200_OK - assert response.data == expected - def test_global_permissions(self): """ If a user does not have global permissions on an action, then any diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -174,7 +174,7 @@ class Meta: TestSerializer\(\): auto_field = IntegerField\(read_only=True\) big_integer_field = IntegerField\(.*\) - boolean_field = BooleanField\(default=False, required=False\) + boolean_field = BooleanField\(required=False\) char_field = CharField\(max_length=100\) comma_separated_integer_field = CharField\(max_length=100, validators=\[<django.core.validators.RegexValidator object>\]\) date_field = DateField\(\) @@ -183,7 +183,7 @@ class Meta: email_field = EmailField\(max_length=100\) float_field = FloatField\(\) integer_field = IntegerField\(.*\) - null_boolean_field = BooleanField\(allow_null=True, default=False, required=False\) + null_boolean_field = BooleanField\(allow_null=True, required=False\) positive_integer_field = IntegerField\(.*\) positive_small_integer_field = IntegerField\(.*\) slug_field = SlugField\(allow_unicode=False, max_length=100\) @@ -210,7 +210,7 @@ class Meta: length_limit_field = CharField\(max_length=12, min_length=3\) blank_field = CharField\(allow_blank=True, max_length=10, required=False\) null_field = IntegerField\(allow_null=True,.*required=False\) - default_field = IntegerField\(default=0,.*required=False\) + default_field = IntegerField\(.*required=False\) descriptive_field = IntegerField\(help_text='Some help text', label='A label'.*\) choices_field = ChoiceField\(choices=(?:\[|\()\('red', 'Red'\), \('blue', 'Blue'\), \('green', 'Green'\)(?:\]|\))\) text_choices_field = ChoiceField\(choices=(?:\[|\()\('red', 'Red'\), \('blue', 'Blue'\), \('green', 'Green'\)(?:\]|\))\)
New handling of default= for ModelSerializer Then changes in #9030 lead to a issue in my implemenation: With 3.14 and its ModelSerializer we could determine if a user was passing a field to the API or not. (Basically we allow setting the DB field to everything EXCEPT the default via the REST API.) Example: ``` class Message(Model): content_type = models.TextField(null=False, blank=False, default="undefined") class MessageSerializer(ModelSerializer): class Meta: model = Message ``` We could de-serialize the JSON `{}` and the validated data didn't contain the default value for content_type. We still can create the model instance from it because there is a default in the database. BUT we disallow actively setting the content_type to `undefined` by checking if `content_type` is in the validated data and refusing a JSON with `{"content_type": "undefined"}`. With 3.15 we can't determine this anymore, yes? Or is there something in the validated data to tell us where the data came from (the JSON the user posted or the models default)?
Okay, I RTFM and I would use `.initial_data` to see if the `content_type` is user provided or not, correct approach? There's another side-effect of this change that leads to a huge breaking change for non-partial updates (PUT) of fields with default values. Previously if you didn't include a field with a default value when doing a PUT request, that field wouldn't get updated. It would just retain its current value, similarly to if you had done a partial update (PATCH) (the reason you're allowed to not pass it in the PUT is that the default leads to it not being required) But now that field gets updated to the default value instead! This seems very dangerous since it could lead to data loss for anyone who's previously not been passing the current value along for all fields with defaults in PUT requests. > There's another side-effect of this change that leads to a huge breaking change for non-partial updates (PUT) of fields with default values. Previously if you didn't include a field with a default value when doing a PUT request, that field wouldn't get updated. It would just retain its current value, similarly to if you had done a partial update (PATCH) (the reason you're allowed to not pass it in the PUT is that the default leads to it not being required) > > But now that field gets updated to the default value instead! This seems very dangerous since it could lead to data loss for anyone who's previously not been passing the current value along for all fields with defaults in PUT requests. Good point.
2024-03-21T23:27:59
encode/django-rest-framework
9,335
encode__django-rest-framework-9335
[ "9334" ]
4f10c4e43ee57f4a2e387e0c8d44d28d21a3621c
diff --git a/rest_framework/versioning.py b/rest_framework/versioning.py --- a/rest_framework/versioning.py +++ b/rest_framework/versioning.py @@ -119,16 +119,15 @@ class NamespaceVersioning(BaseVersioning): def determine_version(self, request, *args, **kwargs): resolver_match = getattr(request, 'resolver_match', None) - if resolver_match is not None and resolver_match.namespace: - # Allow for possibly nested namespaces. - possible_versions = resolver_match.namespace.split(':') - for version in possible_versions: - if self.is_allowed_version(version): - return version - - if not self.is_allowed_version(self.default_version): - raise exceptions.NotFound(self.invalid_version_message) - return self.default_version + if resolver_match is None or not resolver_match.namespace: + return self.default_version + + # Allow for possibly nested namespaces. + possible_versions = resolver_match.namespace.split(':') + for version in possible_versions: + if self.is_allowed_version(version): + return version + raise exceptions.NotFound(self.invalid_version_message) def reverse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra): if request.version is not None:
diff --git a/tests/test_versioning.py b/tests/test_versioning.py --- a/tests/test_versioning.py +++ b/tests/test_versioning.py @@ -272,7 +272,7 @@ class FakeResolverMatch(ResolverMatch): assert response.status_code == status.HTTP_404_NOT_FOUND -class TestAcceptHeaderAllowedAndDefaultVersion: +class TestAllowedAndDefaultVersion: def test_missing_without_default(self): scheme = versioning.AcceptHeaderVersioning view = AllowedVersionsView.as_view(versioning_class=scheme) @@ -318,97 +318,6 @@ def test_missing_with_default_and_none_allowed(self): assert response.data == {'version': 'v2'} -class TestNamespaceAllowedAndDefaultVersion: - def test_no_namespace_without_default(self): - class FakeResolverMatch: - namespace = None - - scheme = versioning.NamespaceVersioning - view = AllowedVersionsView.as_view(versioning_class=scheme) - - request = factory.get('/endpoint/') - request.resolver_match = FakeResolverMatch - response = view(request) - assert response.status_code == status.HTTP_404_NOT_FOUND - - def test_no_namespace_with_default(self): - class FakeResolverMatch: - namespace = None - - scheme = versioning.NamespaceVersioning - view = AllowedAndDefaultVersionsView.as_view(versioning_class=scheme) - - request = factory.get('/endpoint/') - request.resolver_match = FakeResolverMatch - response = view(request) - assert response.status_code == status.HTTP_200_OK - assert response.data == {'version': 'v2'} - - def test_no_match_without_default(self): - class FakeResolverMatch: - namespace = 'no_match' - - scheme = versioning.NamespaceVersioning - view = AllowedVersionsView.as_view(versioning_class=scheme) - - request = factory.get('/endpoint/') - request.resolver_match = FakeResolverMatch - response = view(request) - assert response.status_code == status.HTTP_404_NOT_FOUND - - def test_no_match_with_default(self): - class FakeResolverMatch: - namespace = 'no_match' - - scheme = versioning.NamespaceVersioning - view = AllowedAndDefaultVersionsView.as_view(versioning_class=scheme) - - request = factory.get('/endpoint/') - request.resolver_match = FakeResolverMatch - response = view(request) - assert response.status_code == status.HTTP_200_OK - assert response.data == {'version': 'v2'} - - def test_with_default(self): - class FakeResolverMatch: - namespace = 'v1' - - scheme = versioning.NamespaceVersioning - view = AllowedAndDefaultVersionsView.as_view(versioning_class=scheme) - - request = factory.get('/endpoint/') - request.resolver_match = FakeResolverMatch - response = view(request) - assert response.status_code == status.HTTP_200_OK - assert response.data == {'version': 'v1'} - - def test_no_match_without_default_but_none_allowed(self): - class FakeResolverMatch: - namespace = 'no_match' - - scheme = versioning.NamespaceVersioning - view = AllowedWithNoneVersionsView.as_view(versioning_class=scheme) - - request = factory.get('/endpoint/') - request.resolver_match = FakeResolverMatch - response = view(request) - assert response.status_code == status.HTTP_200_OK - assert response.data == {'version': None} - - def test_no_match_with_default_and_none_allowed(self): - class FakeResolverMatch: - namespace = 'no_match' - - scheme = versioning.NamespaceVersioning - view = AllowedWithNoneAndDefaultVersionsView.as_view(versioning_class=scheme) - - request = factory.get('/endpoint/') - request.resolver_match = FakeResolverMatch - response = view(request) - assert response.status_code == status.HTTP_200_OK - assert response.data == {'version': 'v2'} - - class TestHyperlinkedRelatedField(URLPatternsTestCase, APITestCase): included = [ path('namespaced/<int:pk>/', dummy_pk_view, name='namespaced'),
3.15 regression: Unset default namespace version suddenly raises 404 - The intention of #7278 seems to be to deal with situations where `DEFAULT_VERSION` is ignored. The description of the fix relates to non-`None` values of `DEFAULT_VERSION`. - When `DEFAULT_VERSION` is `None` and `ALLOWED_VERSIONS` is non-empty, [the new code now raises 404](https://github.com/Kostia-K/django-rest-framework/blob/7050b4d36ecc3ce395bc097798af6bf9c99a28f0/rest_framework/versioning.py#L130). - In 3.14, `None` would be returned in this case. This suddenly raises 404 where previously the view was properly run. This is a regression that significantly changes the API. The change should be reverted.
2024-03-22T00:09:37
encode/django-rest-framework
9,338
encode__django-rest-framework-9338
[ "9308" ]
400b4c54419c5c88542ddd0b97219ad4fa8ee29a
diff --git a/rest_framework/filters.py b/rest_framework/filters.py --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -24,15 +24,19 @@ def search_smart_split(search_terms): """generator that first splits string by spaces, leaving quoted phrases together, then it splits non-quoted phrases by commas. """ + split_terms = [] for term in smart_split(search_terms): # trim commas to avoid bad matching for quoted phrases term = term.strip(',') if term.startswith(('"', "'")) and term[0] == term[-1]: # quoted phrases are kept together without any other split - yield unescape_string_literal(term) + split_terms.append(unescape_string_literal(term)) else: # non-quoted tokens are split by comma, keeping only non-empty ones - yield from (sub_term.strip() for sub_term in term.split(',') if sub_term) + for sub_term in term.split(','): + if sub_term: + split_terms.append(sub_term.strip()) + return split_terms class BaseFilterBackend: @@ -85,7 +89,8 @@ def get_search_terms(self, request): """ value = request.query_params.get(self.search_param, '') field = CharField(trim_whitespace=False, allow_blank=True) - return field.run_validation(value) + cleaned_value = field.run_validation(value) + return search_smart_split(cleaned_value) def construct_search(self, field_name, queryset): lookup = self.lookup_prefixes.get(field_name[0]) @@ -163,7 +168,7 @@ def filter_queryset(self, request, queryset, view): reduce( operator.or_, (models.Q(**{orm_lookup: term}) for orm_lookup in orm_lookups) - ) for term in search_smart_split(search_terms) + ) for term in search_terms ) queryset = queryset.filter(reduce(operator.and_, conditions))
3.15 backward compatibility issue with 3.14 - `rest_framework.filters.SearchFilter.get_search_terms` returns `str` instead of `list` ### Discussed in https://github.com/encode/django-rest-framework/discussions/9307 <div type='discussions-op-text'> <sup>Originally posted by **freenoth** March 19, 2024</sup> in 3.14 the `get_search_terms` method of `rest_framework.filters.SearchFilter` class was returning a **list** of terms ![image](https://github.com/encode/django-rest-framework/assets/2629328/05f7b36c-1d06-461e-b7e6-5737b7c03e93) so we were able to iterate the search terms directly ![image](https://github.com/encode/django-rest-framework/assets/2629328/5cc38777-058d-4be5-a237-fa04924f7b49) in 3.15 the same method `get_search_terms` is returning a **string** representation ![image](https://github.com/encode/django-rest-framework/assets/2629328/6c27762a-64eb-42ef-80cc-a80cfcb8ea99) and to convert the `str` to a `list` an additional function was introduced `rest_framework.filters.search_smart_split`: ![image](https://github.com/encode/django-rest-framework/assets/2629328/c6bbb17a-1463-421d-97bd-f41b3cdf7c16) and now we have to use this function to iterate the terms explicitly ![image](https://github.com/encode/django-rest-framework/assets/2629328/f317bd30-948c-4f90-af8e-a73d6390c4f2) So the changing of return value type (and the result itself, actually) can break some custom classes, that are using the basic functionality. Moreover it's hard to figure out what is wrong, because both `list` and `str` are iterable, so the implementation works, but with the wrong results. Example: I had a custom Search filter class based on `rest_framework.filters.SearchFilter` with overrided `filter_queryset` method, so I used the basic method to get the list of search terms ```python search_terms = self.get_search_terms(request) ``` and a simple iteration by search terms works well ```python for search_term in search_terms: ``` but after upgrading to 3.15, my iteration started working differently, because now `get_search_terms` is returning a string -> so it works as iteration by string, it's adding every symbol of this string as independent query, instead of one query for input `?search=asd` it builds a query like that ```sql WHERE ((UPPER("resource"."id"::text) LIKE UPPER(%a%) OR UPPER("resource"."name"::text) LIKE UPPER(%a%)) AND (UPPER("resource"."id"::text) LIKE UPPER(%s%) OR UPPER("resource"."name"::text) LIKE UPPER(%s%)) AND (UPPER("resource"."id"::text) LIKE UPPER(%d%) OR UPPER("resource"."name"::text) LIKE UPPER(%d%))) ``` instead of a single search query ```sql WHERE (UPPER("resource"."id"::text) LIKE UPPER(%asd%) OR UPPER("resource"."name"::text) LIKE UPPER(%asd%)) ``` so we have to add using a `rest_framework.filters.search_smart_split` function explicitly everywhere to iterate search terms in an old way ```python for search_term in search_smart_split(search_terms): ``` is there a chance to use `search_smart_split` inside the `rest_framework.filters.SearchFilter.get_search_terms` to not to break backward compatibility and method behavior?</div>
Suggest reverting #9017. Okay, I can't automatically revert #9017 through the GH interface. If anyone's up for creating the revert PR for that, would be appreciated. I have to look into it
2024-03-22T10:48:05
encode/django-rest-framework
9,339
encode__django-rest-framework-9339
[ "9331" ]
eb361d289deb4bc99ad2ebab9c5f50a92de40339
diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -10,7 +10,7 @@ import django __title__ = 'Django REST framework' -__version__ = '3.15.0' +__version__ = '3.15.1' __author__ = 'Tom Christie' __license__ = 'BSD 3-Clause' __copyright__ = 'Copyright 2011-2023 Encode OSS Ltd'
Version 3.15.1 This is a patch release dealing with a number of unforeseen issues in 3.15.0. Please see https://github.com/encode/django-rest-framework/discussions/9270 for discussion on the project management, and ensuring we're able to get into a much more carefully considered release process for future releases. (In brief: The project should broadly just be tracking Django versions, and dealing with required security fixes. We need a much higher bar to accepting contributions, and need some clear guidelines to help us manage that process with as little noise and churn as possible.) --- *The following change has been fixed*... - [x] #9308 --- *The following changes have all been reverted, for the time being*... - [x] #9319 - Resolved via #9327 - [x] #9317 - Resolved via #9326 - [x] #9310 - Resolved via #9333 - [x] #9306 - Resolved via #9327 - [x] #9299 - Resolved via #9332 - [x] #9295 - Resolved via #9330 - [x] #9300 - Resolved via #9301 - [x] #9334 - Resolved via #9335
Consider adding #9334
2024-03-22T11:15:58
microsoft/promptflow
576
microsoft__promptflow-576
[ "561" ]
8f74874823e3bb4745ccf10a7b7f8309fd889a19
diff --git a/src/promptflow/promptflow/_core/tracer.py b/src/promptflow/promptflow/_core/tracer.py --- a/src/promptflow/promptflow/_core/tracer.py +++ b/src/promptflow/promptflow/_core/tracer.py @@ -5,9 +5,9 @@ import inspect import json import logging +from collections.abc import Iterator from contextvars import ContextVar from datetime import datetime -from types import GeneratorType from typing import Optional from promptflow._core.generator_proxy import GeneratorProxy, generate_from_proxy @@ -106,7 +106,7 @@ def pop(cls, output=None, error: Optional[Exception] = None): def _pop(self, output=None, error: Optional[Exception] = None): last_trace = self._trace_stack[-1] - if isinstance(output, GeneratorType): + if isinstance(output, Iterator): output = GeneratorProxy(output) if output is not None: last_trace.output = self.to_serializable(output)
diff --git a/src/promptflow/tests/executor/unittests/_core/test_generator_proxy.py b/src/promptflow/tests/executor/unittests/_core/test_generator_proxy.py --- a/src/promptflow/tests/executor/unittests/_core/test_generator_proxy.py +++ b/src/promptflow/tests/executor/unittests/_core/test_generator_proxy.py @@ -8,6 +8,10 @@ def generator(): yield i +def iterator(): + return iter([0, 1, 2]) + + @pytest.mark.unittest def test_generator_proxy_next(): proxy = GeneratorProxy(generator()) @@ -42,3 +46,39 @@ def test_generate_from_proxy(): assert i == next(original_generator) assert proxy.items == [0, 1, 2] + + [email protected] +def test_iterator_proxy_next(): + proxy = GeneratorProxy(iterator()) + assert proxy.items == [] + assert next(proxy) == 0 + assert next(proxy) == 1 + assert next(proxy) == 2 + + with pytest.raises(StopIteration): + next(proxy) + + assert proxy.items == [0, 1, 2] + + [email protected] +def test_iterator_proxy_iter(): + original_iterator = iterator() + proxy = GeneratorProxy(iterator()) + + for num in proxy: + assert num == next(original_iterator) + + assert proxy.items == [0, 1, 2] + + [email protected] +def test_generate_from_iterator_proxy(): + proxy = GeneratorProxy(iterator()) + original_iterator = iterator() + + for i in generate_from_proxy(proxy): + assert i == next(original_iterator) + + assert proxy.items == [0, 1, 2]
[BUG] Streaming requires Generator where Iterator should suffice **Describe the bug** For the user code to provide streaming content, instead of the more generic Iterator protocol, Promptflow relies on the more specific `GeneratorType`. That is requiring the user to unnecessarily wrap their iterators in generators to stream content in more generic scenarios (such as streaming langchain results). Is there a reason PF depends on GeneratorType instead of the iterator protocol? Also, see this note in the [python source](https://github.com/python/cpython/blob/f65497fd252a4a4df960da04d68e8316b58624c0/Lib/types.py#L6-L10): ``` # Iterators in Python aren't a matter of type but of protocol. A large # and changing number of builtin types implement *some* flavor of # iterator. Don't check the type! Use hasattr to check for both # "__iter__" and "__next__" attributes instead. ``` **Concrete Issue:** When returning an iterator from my tool to enable streaming, I get the following error when running `pf flow test` ``` Flow test failed with UserErrorException: Exception: The output 'answer' for flow is incorrect. The output value is not JSON serializable. JSON dump failed: (TypeError) Object of type WordIterator is not JSON serializable. Please verify your flow output and make sure the value serializable. ``` **How To Reproduce the bug** Here is my flow.dag.yaml: ```yaml id: template_chat_flow name: Template Chat Flow inputs: chat_history: type: list default: [] question: type: string default: What is the meaning of life? outputs: answer: type: string is_chat_output: true reference: ${stream.output} nodes: - name: stream type: python source: type: code path: stream.py inputs: input: ${inputs.question} ``` And here is my stream.py ```python from promptflow import tool class WordIterator: def __init__(self, input: str): self.input = input def __iter__(self): return self def __next__(self): if self.input: word, *rest = self.input.split(" ") self.input = " ".join(rest) return f"{word} " else: raise StopIteration @tool def my_python_tool(input: str): iterator = WordIterator(input) assert hasattr(iterator, "__iter__") assert hasattr(iterator, "__next__") return iterator ``` With the above PF run `pf flow test --flow .` -- I get this error: ``` 2023-09-19 11:01:17 +0200 42558 execution INFO Start to run 1 nodes with concurrency level 16. 2023-09-19 11:01:17 +0200 42558 execution.flow INFO Executing node stream. node run id: c4ddaddd-6a38-44fd-9ab1-3258fb88bb37_stream_0 2023-09-19 11:01:17 +0200 42558 execution.flow WARNING Output of stream is not json serializable, use str to store it. 2023-09-19 11:01:17 +0200 42558 execution.flow INFO Node stream completes. Flow test failed with UserErrorException: Exception: The output 'answer' for flow is incorrect. The output value is not JSON serializable. JSON dump failed: (TypeError) Object of type WordIterator is not JSON serializable. Please verify your flow output and make sure the value serializable. ``` **Expected behavior** It should read out the iterator and stream the chunks to the caller -- `pf flow test --flow .` should look like this: ``` 2023-09-19 10:34:05 +0200 40375 execution INFO Start to run 1 nodes with concurrency level 16. 2023-09-19 10:34:05 +0200 40375 execution.flow INFO Executing node stream. node run id: 24e60c4d-606a-4fc5-8e4c-cc4a5c41d6c8_stream_0 2023-09-19 10:34:05 +0200 40375 execution.flow WARNING Output of stream is not json serializable, use str to store it. 2023-09-19 10:34:05 +0200 40375 execution.flow INFO Node stream completes. { "answer": "What is the meaning of life? " } ``` **Running Information(please complete the following information):** - Promptflow Package Version using `pf -v`: 0.1.0b6 - Operating System: ``` ProductName: macOS ProductVersion: 13.5.2 BuildVersion: 22G91 ``` - Python Version using `python --version`: Python 3.10.12 **Additional context** If I wrap the iterator in a generator, everything works as expected: ```python from promptflow import tool class WordIterator: def __init__(self, input: str): self.input = input def __iter__(self): return self def __next__(self): if self.input: word, *rest = self.input.split(" ") self.input = " ".join(rest) return f"{word} " else: raise StopIteration def to_generator(self): try: while True: yield next(self) except StopIteration: pass @tool def my_python_tool(input: str): iterator = WordIterator(input).to_generator() assert hasattr(iterator, "__iter__") assert hasattr(iterator, "__next__") return iterator ```
2023-09-20T11:39:29
microsoft/promptflow
3,244
microsoft__promptflow-3244
[ "3243" ]
6ab1286ebcac2bdf0b89a9cea8134d9ee9ae400d
diff --git a/src/promptflow-core/promptflow/_core/token_provider.py b/src/promptflow-core/promptflow/_core/token_provider.py --- a/src/promptflow-core/promptflow/_core/token_provider.py +++ b/src/promptflow-core/promptflow/_core/token_provider.py @@ -4,8 +4,8 @@ from promptflow._utils.credential_utils import get_default_azure_credential -# to access azure ai services, we need to get the token with this audience -COGNITIVE_AUDIENCE = "https://cognitiveservices.azure.com/" +# to access azure ai services, we need to get the token with this scope +COGNITIVE_SCOPE = "https://cognitiveservices.azure.com/.default" class TokenProviderABC(ABC): @@ -48,5 +48,5 @@ def _init_instance(self): ) def get_token(self): - audience = COGNITIVE_AUDIENCE - return self.credential.get_token(audience).token + scope = COGNITIVE_SCOPE + return self.credential.get_token(scope).token
[BUG] Fallback to DefaultAzureCredential isn't compatible with AzureDeveloperCliCredential **Describe the bug** PromptFlow currently falls back to using DefaultAzureCredential and fetching a token for the Oauth 1.0 audience. That is not compatible with all credentials in the chain, specifically, the AzureDeveloperCliCredential which is Oauth 2.0 only. This PR changes the audience value to the correct scope value, and renames variables accordingly. **How To Reproduce the bug** Steps to reproduce the behavior, how frequent can you experience the bug: 1. Run `azd auth login` and DONT login to Azure CLI 2. Run ai-rag-chat-evaluator or other sample code that does *not* specify a credential when using the evaluators/evaluate function PR incoming!
2024-05-13T23:39:14
docarray/docarray
37
docarray__docarray-37
[ "29" ]
e9ce570bb9c2e3312d8ab814014b2cd29a0c249f
diff --git a/docarray/array/document.py b/docarray/array/document.py --- a/docarray/array/document.py +++ b/docarray/array/document.py @@ -146,12 +146,18 @@ def __getitem__( and len(index) == 2 and isinstance(index[0], (slice, Sequence)) ): - _docs = self[index[0]] - _attrs = index[1] - if isinstance(_attrs, str): - _attrs = (index[1],) - - return _docs._get_attributes(*_attrs) + if isinstance(index[0], str) and isinstance(index[1], str): + # ambiguity only comes from the second string + if index[1] in self._id2offset: + return DocumentArray([self[index[0]], self[index[1]]]) + else: + return getattr(self[index[0]], index[1]) + elif isinstance(index[0], (slice, Sequence)): + _docs = self[index[0]] + _attrs = index[1] + if isinstance(_attrs, str): + _attrs = (index[1],) + return _docs._get_attributes(*_attrs) elif isinstance(index[0], bool): return DocumentArray(itertools.compress(self._data, index)) elif isinstance(index[0], int): @@ -231,31 +237,45 @@ def __setitem__( and len(index) == 2 and isinstance(index[0], (slice, Sequence)) ): - _docs = self[index[0]] - _attrs = index[1] - - if isinstance(_attrs, str): - # a -> [a] - # [a, a] -> [a, a] - _attrs = (index[1],) - if isinstance(value, (list, tuple)) and not any( - isinstance(el, (tuple, list)) for el in value - ): - # [x] -> [[x]] - # [[x], [y]] -> [[x], [y]] - value = (value,) - if not isinstance(value, (list, tuple)): - # x -> [x] - value = (value,) - - for _a, _v in zip(_attrs, value): - if _a == 'blob': - _docs.blobs = _v - elif _a == 'embedding': - _docs.embeddings = _v + if isinstance(index[0], str) and isinstance(index[1], str): + # ambiguity only comes from the second string + if index[1] in self._id2offset: + for _d, _v in zip((self[index[0]], self[index[1]]), value): + _d._data = _v._data + self._rebuild_id2offset() + elif hasattr(self[index[0]], index[1]): + setattr(self[index[0]], index[1], value) else: - for _d, _vv in zip(_docs, _v): - setattr(_d, _a, _vv) + # to avoid accidentally add new unsupport attribute + raise ValueError( + f'`{index[1]}` is neither a valid id nor attribute name' + ) + elif isinstance(index[0], (slice, Sequence)): + _docs = self[index[0]] + _attrs = index[1] + + if isinstance(_attrs, str): + # a -> [a] + # [a, a] -> [a, a] + _attrs = (index[1],) + if isinstance(value, (list, tuple)) and not any( + isinstance(el, (tuple, list)) for el in value + ): + # [x] -> [[x]] + # [[x], [y]] -> [[x], [y]] + value = (value,) + if not isinstance(value, (list, tuple)): + # x -> [x] + value = (value,) + + for _a, _v in zip(_attrs, value): + if _a == 'blob': + _docs.blobs = _v + elif _a == 'embedding': + _docs.embeddings = _v + else: + for _d, _vv in zip(_docs, _v): + setattr(_d, _a, _vv) elif isinstance(index[0], bool): if len(index) != len(self._data): raise IndexError( @@ -313,12 +333,20 @@ def __delitem__(self, index: 'DocumentArrayIndexType'): and len(index) == 2 and isinstance(index[0], (slice, Sequence)) ): - _docs = self[index[0]] - _attrs = index[1] - if isinstance(_attrs, str): - _attrs = (index[1],) - for _d in _docs: - _d.pop(*_attrs) + if isinstance(index[0], str) and isinstance(index[1], str): + # ambiguity only comes from the second string + if index[1] in self._id2offset: + del self[index[0]] + del self[index[1]] + else: + self[index[0]].pop(index[1]) + elif isinstance(index[0], (slice, Sequence)): + _docs = self[index[0]] + _attrs = index[1] + if isinstance(_attrs, str): + _attrs = (index[1],) + for _d in _docs: + _d.pop(*_attrs) elif isinstance(index[0], bool): self._data = list( itertools.compress(self._data, (not _i for _i in index))
diff --git a/tests/unit/array/test_advance_indexing.py b/tests/unit/array/test_advance_indexing.py --- a/tests/unit/array/test_advance_indexing.py +++ b/tests/unit/array/test_advance_indexing.py @@ -222,8 +222,6 @@ def test_advance_selector_mixed(): def test_single_boolean_and_padding(): - from docarray import DocumentArray - da = DocumentArray.empty(3) with pytest.raises(IndexError): @@ -237,3 +235,41 @@ def test_single_boolean_and_padding(): assert len(da[True, False]) == 1 assert len(da[False, False]) == 0 + + +def test_edge_case_two_strings(): + # getitem + da = DocumentArray([Document(id='1'), Document(id='2'), Document(id='3')]) + assert da['1', 'id'] == '1' + assert len(da['1', '2']) == 2 + assert isinstance(da['1', '2'], DocumentArray) + with pytest.raises(KeyError): + da['hello', '2'] + with pytest.raises(AttributeError): + da['1', 'hello'] + assert len(da['1', '2', '3']) == 3 + assert isinstance(da['1', '2', '3'], DocumentArray) + + # delitem + del da['1', '2'] + assert len(da) == 1 + + da = DocumentArray([Document(id='1'), Document(id='2'), Document(id='3')]) + del da['1', 'id'] + assert len(da) == 3 + assert not da[0].id + + del da['2', 'hello'] + + # setitem + da = DocumentArray([Document(id='1'), Document(id='2'), Document(id='3')]) + da['1', '2'] = DocumentArray.empty(2) + assert da[0].id != '1' + assert da[1].id != '2' + + da = DocumentArray([Document(id='1'), Document(id='2'), Document(id='3')]) + da['1', 'text'] = 'hello' + assert da['1'].text == 'hello' + + with pytest.raises(ValueError): + da['1', 'hellohello'] = 'hello'
fix(array): fix getting docs by two ids The `DocumentArray` method `__getitem__` is incorrect in the case two ids are passed: Minimal working example to showcase bug: ```python In [2]: from docarray import Document, DocumentArray ...: ...: da = DocumentArray([Document(id='1'), ...: Document(id='2'), ...: Document(id='3')]) ``` Currently selecting with two doc ids produces ```python In [4]: da['1','2'] --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /var/folders/05/h71x7gh54sx_5y43ppkq9_dw0000gq/T/ipykernel_8535/2066379862.py in <module> ----> 1 da['1','2'] ~/Documents/jina_stuff/docarray/docarray/array/document.py in __getitem__(self, index) 151 if isinstance(_attrs, str): 152 _attrs = (index[1],) --> 153 return _docs._get_attributes(*_attrs) 154 elif isinstance(index[0], bool): 155 return DocumentArray(itertools.compress(self._data, index)) ~/Documents/jina_stuff/docarray/docarray/document/mixins/attribute.py in _get_attributes(self, *fields) 20 value = dunder_get(self, k) 21 else: ---> 22 value = getattr(self, k) 23 24 ret.append(value) AttributeError: 'Document' object has no attribute '2' ``` This PR solves this and produces ```python In [3]: da['1'] Out[3]: <Document ('id',) at 1> In [4]: da['1','2'] Out[4]: <DocumentArray (length=2) at 140552956821312> In [5]: da['1','2','3'] Out[5]: <DocumentArray (length=3) at 140552956819056> ```
# [Codecov](https://codecov.io/gh/jina-ai/docarray/pull/29?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) Report > Merging [#29](https://codecov.io/gh/jina-ai/docarray/pull/29?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) (0fd2c7c) into [main](https://codecov.io/gh/jina-ai/docarray/commit/79ad2362df1e67d401dac19e1af5156c7959aaea?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) (79ad236) will **increase** coverage by `0.18%`. > The diff coverage is `100.00%`. [![Impacted file tree graph](https://codecov.io/gh/jina-ai/docarray/pull/29/graphs/tree.svg?width=650&height=150&src=pr&token=9WGcGyyqtI&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai)](https://codecov.io/gh/jina-ai/docarray/pull/29?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) ```diff @@ Coverage Diff @@ ## main #29 +/- ## ========================================== + Coverage 83.09% 83.27% +0.18% ========================================== Files 67 67 Lines 3135 3151 +16 ========================================== + Hits 2605 2624 +19 + Misses 530 527 -3 ``` | Flag | Coverage Δ | | |---|---|---| | docarray | `83.27% <100.00%> (+0.18%)` | :arrow_up: | Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai#carryforward-flags-in-the-pull-request-comment) to find out more. | [Impacted Files](https://codecov.io/gh/jina-ai/docarray/pull/29?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) | Coverage Δ | | |---|---|---| | [docarray/array/document.py](https://codecov.io/gh/jina-ai/docarray/pull/29/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai#diff-ZG9jYXJyYXkvYXJyYXkvZG9jdW1lbnQucHk=) | `85.77% <100.00%> (+1.52%)` | :arrow_up: | | [docarray/proto/io/ndarray.py](https://codecov.io/gh/jina-ai/docarray/pull/29/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai#diff-ZG9jYXJyYXkvcHJvdG8vaW8vbmRhcnJheS5weQ==) | `94.78% <0.00%> (+0.09%)` | :arrow_up: | | [docarray/array/mixins/io/binary.py](https://codecov.io/gh/jina-ai/docarray/pull/29/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai#diff-ZG9jYXJyYXkvYXJyYXkvbWl4aW5zL2lvL2JpbmFyeS5weQ==) | `95.55% <0.00%> (+0.31%)` | :arrow_up: | | [docarray/document/mixins/porting.py](https://codecov.io/gh/jina-ai/docarray/pull/29/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai#diff-ZG9jYXJyYXkvZG9jdW1lbnQvbWl4aW5zL3BvcnRpbmcucHk=) | `92.59% <0.00%> (+0.92%)` | :arrow_up: | ------ [Continue to review full report at Codecov](https://codecov.io/gh/jina-ai/docarray/pull/29?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/jina-ai/docarray/pull/29?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai). Last update [79ad236...0fd2c7c](https://codecov.io/gh/jina-ai/docarray/pull/29?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai). I think `da['1','2']` is confusing. It is not clear whether we want to select by `id` or to select attributes. Anyway, the part of selecting by ids does not work. I suggest remove this part for the time being. ![image](https://user-images.githubusercontent.com/4329072/149073652-28eda642-ebfc-42f0-92b0-b6732f50ca6b.png) MWE: ```python from docarray import Document, DocumentArray da = DocumentArray([Document(id='1'), Document(id='2'), Document(id='3')]) da['1', '2'] ``` leads to the error, ```bash Traceback (most recent call last): File "/Users/nanwang/Codes/jina-ai/docarray/toys/toy2.py", line 7, in <module> print(da['1', '2']) File "/Users/nanwang/Codes/jina-ai/docarray/docarray/array/document.py", line 154, in __getitem__ return _docs._get_attributes(*_attrs) File "/Users/nanwang/Codes/jina-ai/docarray/docarray/document/mixins/attribute.py", line 22, in _get_attributes value = getattr(self, k) AttributeError: 'Document' object has no attribute '2' ``` One principle we can stick to is to use the first arg to select ids\index\slices and the second arg to select the attributes. If we follow this rule, the grammar for selecting by integers should be refactored to ```diff - da[1, 2, 3] + da[[1, 2, 3]] ``` This pattern is similar as the pandas `DataFrame.loc`. **The `id` in DocArray is equivalent to `index` in `pandas.DataFrame`.** Here is an example ```python import pandas as pd df = pd.DataFrame([['a', 1, 'xx'], ['b', 2, 'xx'], ['c', 3, 'xx']], columns=['name', 'age', 'place']) df.set_index('name', inplace=True) # select by one id print(df.loc['a']) """output age 1 place xx Name: a, dtype: object age place """ # select by multiple ids print(df.loc[['a', 'b']]) """output name a 1 xx b 2 xx 1 """ # select by one id & one attribute print(df.loc['a', 'age']) """output 1 """ # select by multiple ids & one attribute print(df.loc[['a', 'b'], 'age']) """output name a 1 b 2 Name: age, dtype: int64 """ # select by multiple ids & multiple attribute print(df.loc[['a', 'b'], ['age', 'place']]) """output age place name a 1 xx b 2 xx """ ``` This error that you point out @nan-wang is precisely what I explain in the example on top of the PR and should be solved by the PR.
2022-01-12T10:16:46
docarray/docarray
60
docarray__docarray-60
[ "59" ]
f5c013fcadfa4f1f13bb1c3fb4e3b5ed9f9804e9
diff --git a/docarray/document/pydantic_model.py b/docarray/document/pydantic_model.py --- a/docarray/document/pydantic_model.py +++ b/docarray/document/pydantic_model.py @@ -7,7 +7,8 @@ if TYPE_CHECKING: from ..types import ArrayType -_ProtoValueType = Optional[Union[str, bool, float]] +# this order must be preserved: https://pydantic-docs.helpmanual.io/usage/types/#unions +_ProtoValueType = Optional[Union[bool, float, str]] _StructValueType = Union[ _ProtoValueType, List[_ProtoValueType], Dict[str, _ProtoValueType] ]
diff --git a/tests/__init__.py b/tests/__init__.py --- a/tests/__init__.py +++ b/tests/__init__.py @@ -20,7 +20,7 @@ def random_docs( d = Document(id=doc_id) d.text = text - d.tags['id'] = doc_id + d.tags['id'] = f'myself id is: {doc_id}' if embedding: if sparse_embedding: from scipy.sparse import coo_matrix @@ -42,8 +42,8 @@ def random_docs( c.embedding = np.random.random( [embed_dim + np.random.randint(0, jitter)] ) - c.tags['parent_id'] = doc_id - c.tags['id'] = chunk_doc_id + c.tags['parent_id'] = f'my parent is: {id}' + c.tags['id'] = f'myself id is: {doc_id}' d.chunks.append(c) next_chunk_doc_id += 1 diff --git a/tests/unit/test_pydantic.py b/tests/unit/test_pydantic.py --- a/tests/unit/test_pydantic.py +++ b/tests/unit/test_pydantic.py @@ -2,6 +2,7 @@ from typing import List, Optional import numpy as np +import pytest from fastapi import FastAPI from pydantic import BaseModel from starlette.testclient import TestClient @@ -116,3 +117,28 @@ def test_match_to_from_pydantic(): def test_with_embedding_no_tensor(): d = Document(embedding=np.random.rand(2, 2)) PydanticDocument.parse_obj(d.to_pydantic_model().dict()) + + [email protected]( + 'tag_value, tag_type', + [(3, float), (3.4, float), ('hello', str), (True, bool), (False, bool)], +) [email protected]('protocol', ['protobuf', 'jsonschema']) +def test_tags_int_float_str_bool(tag_type, tag_value, protocol): + d = Document(tags={'hello': tag_value}) + dd = d.to_dict(protocol=protocol)['tags']['hello'] + assert dd == tag_value + assert isinstance(dd, tag_type) + + # now nested tags in dict + + d = Document(tags={'hello': {'world': tag_value}}) + dd = d.to_dict(protocol=protocol)['tags']['hello']['world'] + assert dd == tag_value + assert isinstance(dd, tag_type) + + # now nested in list + d = Document(tags={'hello': [tag_value] * 10}) + dd = d.to_dict(protocol=protocol)['tags']['hello'][-1] + assert dd == tag_value + assert isinstance(dd, tag_type)
fix: fix tags type after pydantic model
2022-01-18T13:39:18
docarray/docarray
66
docarray__docarray-66
[ "64" ]
624b5032a03863217f04997bfabb13cae438de20
diff --git a/docarray/array/mixins/plot.py b/docarray/array/mixins/plot.py --- a/docarray/array/mixins/plot.py +++ b/docarray/array/mixins/plot.py @@ -108,6 +108,7 @@ def plot_embeddings( start_server: bool = True, host: str = '127.0.0.1', port: Optional[int] = None, + image_source: str = 'tensor', ) -> str: """Interactively visualize :attr:`.embeddings` using the Embedding Projector. @@ -121,6 +122,7 @@ def plot_embeddings( :param min_image_size: only used when `image_sprites=True`. the minimum size of the image :param channel_axis: only used when `image_sprites=True`. the axis id of the color channel, ``-1`` indicates the color channel info at the last axis :param start_server: if set, start a HTTP server and open the frontend directly. Otherwise, you need to rely on ``return`` path and serve by yourself. + :param image_source: specify where the image comes from, can be ``uri`` or ``tensor``. empty tensor will fallback to uri :return: the path to the embeddings visualization info. """ from ...helper import random_port, __resources_path__ @@ -154,6 +156,7 @@ def plot_embeddings( canvas_size=canvas_size, min_size=min_image_size, channel_axis=channel_axis, + image_source=image_source, ) self.save_embeddings_csv(os.path.join(path, emb_fn), delimiter='\t') @@ -287,6 +290,7 @@ def plot_image_sprites( canvas_size: int = 512, min_size: int = 16, channel_axis: int = -1, + image_source: str = 'tensor', ) -> None: """Generate a sprite image for all image tensors in this DocumentArray-like object. @@ -297,6 +301,7 @@ def plot_image_sprites( :param canvas_size: the size of the canvas :param min_size: the minimum size of the image :param channel_axis: the axis id of the color channel, ``-1`` indicates the color channel info at the last axis + :param image_source: specify where the image comes from, can be ``uri`` or ``tensor``. empty tensor will fallback to uri """ if not self: raise ValueError(f'{self!r} is empty') @@ -316,26 +321,36 @@ def plot_image_sprites( [img_size * img_per_row, img_size * img_per_row, 3], dtype='uint8' ) img_id = 0 - for d in self: - _d = copy.deepcopy(d) - if _d.content_type != 'tensor': - _d.load_uri_to_image_tensor() - channel_axis = -1 - - _d.set_image_tensor_channel_axis(channel_axis, -1).set_image_tensor_shape( - shape=(img_size, img_size) - ) - - row_id = floor(img_id / img_per_row) - col_id = img_id % img_per_row - sprite_img[ - (row_id * img_size) : ((row_id + 1) * img_size), - (col_id * img_size) : ((col_id + 1) * img_size), - ] = _d.tensor - - img_id += 1 - if img_id >= max_num_img: - break + try: + for d in self: + _d = copy.deepcopy(d) + + if image_source == 'uri' or ( + image_source == 'tensor' and _d.content_type != 'tensor' + ): + _d.load_uri_to_image_tensor() + channel_axis = -1 + elif image_source not in ('uri', 'tensor'): + raise ValueError(f'image_source can be only `uri` or `tensor`') + + _d.set_image_tensor_channel_axis( + channel_axis, -1 + ).set_image_tensor_shape(shape=(img_size, img_size)) + + row_id = floor(img_id / img_per_row) + col_id = img_id % img_per_row + sprite_img[ + (row_id * img_size) : ((row_id + 1) * img_size), + (col_id * img_size) : ((col_id + 1) * img_size), + ] = _d.tensor + + img_id += 1 + if img_id >= max_num_img: + break + except Exception as ex: + raise ValueError( + 'Bad image tensor. Try different `image_source` or `channel_axis`' + ) from ex from PIL import Image
diff --git a/tests/unit/array/mixins/test_plot.py b/tests/unit/array/mixins/test_plot.py --- a/tests/unit/array/mixins/test_plot.py +++ b/tests/unit/array/mixins/test_plot.py @@ -8,7 +8,7 @@ from docarray import DocumentArray, Document -def test_sprite_image_generator(pytestconfig, tmpdir): +def test_sprite_fail_tensor_success_uri(pytestconfig, tmpdir): da = DocumentArray.from_files( [ f'{pytestconfig.rootdir}/**/*.png', @@ -16,7 +16,26 @@ def test_sprite_image_generator(pytestconfig, tmpdir): f'{pytestconfig.rootdir}/**/*.jpeg', ] ) - da.plot_image_sprites(tmpdir / 'sprint_da.png') + da.apply( + lambda d: d.load_uri_to_image_tensor().set_image_tensor_channel_axis(-1, 0) + ) + with pytest.raises(ValueError): + da.plot_image_sprites() + da.plot_image_sprites(tmpdir / 'sprint_da.png', image_source='uri') + assert os.path.exists(tmpdir / 'sprint_da.png') + + [email protected]('image_source', ['tensor', 'uri']) +def test_sprite_image_generator(pytestconfig, tmpdir, image_source): + da = DocumentArray.from_files( + [ + f'{pytestconfig.rootdir}/**/*.png', + f'{pytestconfig.rootdir}/**/*.jpg', + f'{pytestconfig.rootdir}/**/*.jpeg', + ] + ) + da.apply(lambda d: d.load_uri_to_image_tensor()) + da.plot_image_sprites(tmpdir / 'sprint_da.png', image_source=image_source) assert os.path.exists(tmpdir / 'sprint_da.png')
`plot_embeddings` with `image_sprites` from uri **To produce:** ```python from docarray import DocumentArray, Document import torchvision def preproc(d: Document): return (d.load_uri_to_image_tensor() .set_image_tensor_shape((200, 200)) .set_image_tensor_normalization() .set_image_tensor_channel_axis(-1, 0)) left_da = DocumentArray.from_files('left/*.jpg') left_da.apply(preproc) model = torchvision.models.resnet50(pretrained=True) left_da.embed(model) left_da.plot_embeddings(image_sprites=True) ``` Error: ``` --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [1], in <module> 14 model = torchvision.models.resnet50(pretrained=True) 15 left_da.embed(model) ---> 17 left_da.plot_embeddings(image_sprites=True) File ~/workplaces/docarray-env/docarray/docarray/array/mixins/plot.py:152, in PlotMixin.plot_embeddings(self, title, path, image_sprites, min_image_size, channel_axis, start_server, host, port) 140 if len(self) > max_docs: 141 warnings.warn( 142 f''' 143 {self!r} has more than {max_docs} elements, which is the maximum number of image sprites can support. (...) 149 ''' 150 ) --> 152 self.plot_image_sprites( 153 os.path.join(path, sprite_fn), 154 canvas_size=canvas_size, 155 min_size=min_image_size, 156 channel_axis=channel_axis, 157 ) 159 self.save_embeddings_csv(os.path.join(path, emb_fn), delimiter='\t') 161 _exclude_fields = ('embedding', 'tensor', 'scores') File ~/workplaces/docarray-env/docarray/docarray/array/mixins/plot.py:331, in PlotMixin.plot_image_sprites(self, output, canvas_size, min_size, channel_axis) 329 row_id = floor(img_id / img_per_row) 330 col_id = img_id % img_per_row --> 331 sprite_img[ 332 (row_id * img_size) : ((row_id + 1) * img_size), 333 (col_id * img_size) : ((col_id + 1) * img_size), 334 ] = _d.tensor 336 img_id += 1 337 if img_id >= max_num_img: ValueError: could not broadcast input array from shape (16,16,200) into shape (16,16,3) ``` **Suggested fix:** passing `use_uri` flag to `plot_embeddings` to allow visualizing the dots using `uri` attribute. I would be happy to raise a PR for this.
the broadcast issue can be resolved by changing the channel axis using `channel_axis=0` but this will not visualize the original images. > the broadcast issue can be resolved by checking the channel axis using `channel_axis=0` but this will not visualize the original images. maybe u can transform the axis back before plotting? I guess the `stacking` is only needed at `embedding` time > maybe u can transform the axis back before plotting? I guess the `stacking` is only needed at `embedding` time Changing the axis will work , however , it would be nice to have an option to show the original images when projecting embeddings without processing them again. More than the original, you expect plot_embeddings to force some axis as the channel one? > More than the original, you expect plot_embeddings to force some axis as the channel one? just a flag to force loading from uri and setting the channel axis: https://github.com/jina-ai/docarray/blob/79c13a09980c97c9b4fcf9857566ff2a46c95c83/docarray/array/mixins/plot.py#L321 ```python if use_uri or _d.content_type != 'tensor': _d.load_uri_to_image_tensor() channel_axis = -1 ``` Another possible approach for this problem. As the applied `preproc` function is only for model inference. Can we make it possible to pass the `prepoc` function to `. embed()`: ```python def preproc(d: Document) .... return d da.embed(model, preproc_fn=preproc) ``` Then, the output (copy of the origin DA) of `preproc` can then be fed into the model for inference, and will not change the value of origin DA. With this change, the user can choose which method to use regarding context. If the user wants to store the updates, then apply `preproc` before `.embed()`. If the user don't want keep the updates, then apply the `preproc` within the `.embed()`
2022-01-19T07:54:16
docarray/docarray
85
docarray__docarray-85
[ "84" ]
1ed4ddd57163b22c570482168fe274e550553b2d
diff --git a/docarray/document/mixins/featurehash.py b/docarray/document/mixins/featurehash.py --- a/docarray/document/mixins/featurehash.py +++ b/docarray/document/mixins/featurehash.py @@ -64,22 +64,24 @@ def _hash_column(col_name, col_val, n_dim, max_value, idxs, data, table): def _any_hash(v): - try: - return int(v) # parse int parameter - except ValueError: + if not v: + # ignore it when the parameter is empty + return 0 + elif isinstance(v, (tuple, dict, list, str)): + if isinstance(v, str): + v = v.strip() + if v.lower() in {'true', 'yes'}: # parse boolean parameter + return 1 + if v.lower() in {'false', 'no'}: + return 0 + else: + v = json.dumps(v, sort_keys=True) + return int(hashlib.md5(str(v).encode('utf-8')).hexdigest(), base=16) + else: try: - return float(v) # parse float parameter + return int(v) # parse int parameter except ValueError: - if not v: - # ignore it when the parameter is empty - return 0 - if isinstance(v, str): - v = v.strip() - if v.lower() in {'true', 'yes'}: # parse boolean parameter - return 1 - if v.lower() in {'false', 'no'}: - return 0 - if isinstance(v, (tuple, dict, list)): - v = json.dumps(v, sort_keys=True) - - return int(hashlib.md5(str(v).encode('utf-8')).hexdigest(), base=16) + try: + return float(v) # parse float parameter + except ValueError: + return 0 # unable to hash
diff --git a/tests/unit/document/test_feature_hashing.py b/tests/unit/document/test_feature_hashing.py --- a/tests/unit/document/test_feature_hashing.py +++ b/tests/unit/document/test_feature_hashing.py @@ -8,10 +8,17 @@ @pytest.mark.parametrize('sparse', [True, False]) @pytest.mark.parametrize('metric', ['jaccard', 'cosine']) def test_feature_hashing(n_dim, sparse, metric): - da = DocumentArray.empty(3) - da.texts = ['hello world', 'world, bye', 'hello bye'] + da = DocumentArray.empty(6) + da.texts = [ + 'hello world', + 'world, bye', + 'hello bye', + 'infinity test', + 'nan test', + '2.3 test', + ] da.apply(lambda d: d.embed_feature_hashing(n_dim=n_dim, sparse=sparse)) - assert da.embeddings.shape == (3, n_dim) + assert da.embeddings.shape == (6, n_dim) da.embeddings = to_numpy_array(da.embeddings) da.match(da, metric=metric, use_scipy=True) result = da['@m', ('id', f'scores__{metric}__value')]
fix(hashing): ignore casting to float Fixes #83 ```python >>> x = Document(text="float test 2.56") >>> x.get_vocabulary() Counter({'float': 1, 'test': 1, '2': 1, '56': 1}) ```
# [Codecov](https://codecov.io/gh/jina-ai/docarray/pull/84?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) Report > Merging [#84](https://codecov.io/gh/jina-ai/docarray/pull/84?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) (645b1df) into [main](https://codecov.io/gh/jina-ai/docarray/commit/1ed4ddd57163b22c570482168fe274e550553b2d?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) (1ed4ddd) will **decrease** coverage by `0.01%`. > The diff coverage is `66.66%`. [![Impacted file tree graph](https://codecov.io/gh/jina-ai/docarray/pull/84/graphs/tree.svg?width=650&height=150&src=pr&token=9WGcGyyqtI&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai)](https://codecov.io/gh/jina-ai/docarray/pull/84?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) ```diff @@ Coverage Diff @@ ## main #84 +/- ## ========================================== - Coverage 82.98% 82.97% -0.02% ========================================== Files 87 87 Lines 3814 3811 -3 ========================================== - Hits 3165 3162 -3 Misses 649 649 ``` | Flag | Coverage Δ | | |---|---|---| | docarray | `82.97% <66.66%> (-0.02%)` | :arrow_down: | Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai#carryforward-flags-in-the-pull-request-comment) to find out more. | [Impacted Files](https://codecov.io/gh/jina-ai/docarray/pull/84?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) | Coverage Δ | | |---|---|---| | [docarray/document/mixins/featurehash.py](https://codecov.io/gh/jina-ai/docarray/pull/84/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai#diff-ZG9jYXJyYXkvZG9jdW1lbnQvbWl4aW5zL2ZlYXR1cmVoYXNoLnB5) | `87.75% <66.66%> (-0.71%)` | :arrow_down: | ------ [Continue to review full report at Codecov](https://codecov.io/gh/jina-ai/docarray/pull/84?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai). > **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai) > `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data` > Powered by [Codecov](https://codecov.io/gh/jina-ai/docarray/pull/84?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai). Last update [1ed4ddd...645b1df](https://codecov.io/gh/jina-ai/docarray/pull/84?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=jina-ai).
2022-01-27T08:01:48
docarray/docarray
296
docarray__docarray-296
[ "290" ]
1b2703c042b0fc7c3234c8abc34a076dc5e2a331
diff --git a/docarray/array/storage/weaviate/backend.py b/docarray/array/storage/weaviate/backend.py --- a/docarray/array/storage/weaviate/backend.py +++ b/docarray/array/storage/weaviate/backend.py @@ -13,13 +13,13 @@ import numpy as np import weaviate -from ..base.backend import BaseBackendMixin -from ..registry import _REGISTRY from .... import Document from ....helper import dataclass_from_dict, filter_dict +from ..base.backend import BaseBackendMixin +from ..registry import _REGISTRY if TYPE_CHECKING: - from ....typing import DocumentArraySourceType, ArrayType + from ....typing import ArrayType, DocumentArraySourceType @dataclass @@ -35,6 +35,7 @@ class WeaviateConfig: n_dim: Optional[int] = None # deprecated, not used anymore since weaviate 1.10 ef: Optional[int] = None ef_construction: Optional[int] = None + timeout_config: Optional[Tuple[int, int]] = None max_connections: Optional[int] = None @@ -72,7 +73,8 @@ def _init_storage( self._persist = bool(config.name) self._client = weaviate.Client( - f'{config.protocol}://{config.host}:{config.port}' + f'{config.protocol}://{config.host}:{config.port}', + timeout_config=config.timeout_config, ) self._config = config
Expose Timeout Parameters in weaviate Weaviate storage currently does not allow specifying the Timeout parameters. Add the parameter to `WeaviateConfig` and used when creating the weaviate client
2022-04-22T10:31:58
docarray/docarray
359
docarray__docarray-359
[ "358" ]
24301254d95fd755fb6e821df6bc2c6b977b138b
diff --git a/docarray/array/storage/weaviate/backend.py b/docarray/array/storage/weaviate/backend.py --- a/docarray/array/storage/weaviate/backend.py +++ b/docarray/array/storage/weaviate/backend.py @@ -45,6 +45,7 @@ class WeaviateConfig: flat_search_cutoff: Optional[int] = None cleanup_interval_seconds: Optional[int] = None skip: Optional[bool] = None + distance: Optional[str] = None class BackendMixin(BaseBackendMixin): @@ -135,6 +136,7 @@ def _get_schema_by_name(self, cls_name: str) -> Dict: 'flatSearchCutoff': self._config.flat_search_cutoff, 'cleanupIntervalSeconds': self._config.cleanup_interval_seconds, 'skip': self._config.skip, + 'distance': self._config.distance, } return {
diff --git a/tests/unit/array/docker-compose.yml b/tests/unit/array/docker-compose.yml --- a/tests/unit/array/docker-compose.yml +++ b/tests/unit/array/docker-compose.yml @@ -1,7 +1,7 @@ version: "3.3" services: weaviate: - image: semitechnologies/weaviate:1.11.0 + image: semitechnologies/weaviate:1.13.2 ports: - "8080:8080" environment: diff --git a/tests/unit/array/test_backend_configuration.py b/tests/unit/array/test_backend_configuration.py --- a/tests/unit/array/test_backend_configuration.py +++ b/tests/unit/array/test_backend_configuration.py @@ -18,6 +18,7 @@ def test_weaviate_hnsw(start_storage): 'flat_search_cutoff': 20000, 'cleanup_interval_seconds': 1000, 'skip': True, + 'distance': 'l2-squared', }, ) @@ -43,3 +44,4 @@ def test_weaviate_hnsw(start_storage): assert main_class.get('vectorIndexConfig', {}).get('flatSearchCutoff') == 20000 assert main_class.get('vectorIndexConfig', {}).get('cleanupIntervalSeconds') == 1000 assert main_class.get('vectorIndexConfig', {}).get('skip') is True + assert main_class.get('vectorIndexConfig', {}).get('distance') == 'l2-squared'
Configure Distance Metric in Weaviate As discussed over Slack, when Weaviate supports different distance metrics other than `cosine` they need to be configurable in doc array as well.
I will provide a PR for this.
2022-05-20T12:33:55
docarray/docarray
394
docarray__docarray-394
[ "393" ]
ae4d63b8e15f8c6e5ae65f9b1bcff8d9f4fe44c4
diff --git a/docarray/dataclasses/types.py b/docarray/dataclasses/types.py --- a/docarray/dataclasses/types.py +++ b/docarray/dataclasses/types.py @@ -234,23 +234,23 @@ def _from_document(cls: Type['T'], doc: 'Document') -> 'T': ]: attributes[key] = doc.tags[key] elif attribute_info['attribute_type'] == AttributeType.DOCUMENT: - attribute_doc = doc.chunks[position] + attribute_doc = doc.chunks[int(position)] attribute = _get_doc_attribute(attribute_doc, field) attributes[key] = attribute elif attribute_info['attribute_type'] == AttributeType.ITERABLE_DOCUMENT: attribute_list = [] - for chunk_doc in doc.chunks[position].chunks: + for chunk_doc in doc.chunks[int(position)].chunks: attribute_list.append(_get_doc_attribute(chunk_doc, field)) attributes[key] = attribute_list elif attribute_info['attribute_type'] == AttributeType.NESTED: nested_cls = field.type attributes[key] = _get_doc_nested_attribute( - doc.chunks[position], nested_cls + doc.chunks[int(position)], nested_cls ) elif attribute_info['attribute_type'] == AttributeType.ITERABLE_NESTED: nested_cls = cls.__dataclass_fields__[key].type.__args__[0] attribute_list = [] - for chunk_doc in doc.chunks[position].chunks: + for chunk_doc in doc.chunks[int(position)].chunks: attribute_list.append(_get_doc_nested_attribute(chunk_doc, nested_cls)) attributes[key] = attribute_list else: diff --git a/docarray/document/mixins/multimodal.py b/docarray/document/mixins/multimodal.py --- a/docarray/document/mixins/multimodal.py +++ b/docarray/document/mixins/multimodal.py @@ -116,12 +116,12 @@ def get_multi_modal_attribute(self, attribute: str) -> 'DocumentArray': position = self._metadata['multi_modal_schema'][attribute].get('position') if attribute_type in [AttributeType.DOCUMENT, AttributeType.NESTED]: - return DocumentArray([self.chunks[position]]) + return DocumentArray([self.chunks[int(position)]]) elif attribute_type in [ AttributeType.ITERABLE_DOCUMENT, AttributeType.ITERABLE_NESTED, ]: - return self.chunks[position].chunks + return self.chunks[int(position)].chunks else: raise ValueError( f'Invalid attribute {attribute}: must a Document attribute or nested dataclass'
diff --git a/tests/unit/document/test_multi_modal.py b/tests/unit/document/test_multi_modal.py --- a/tests/unit/document/test_multi_modal.py +++ b/tests/unit/document/test_multi_modal.py @@ -482,6 +482,12 @@ class MMDocument: assert deserialized_doc.chunks[1].tensor.shape == (10, 10, 3) assert deserialized_doc.tags['version'] == 20 + images = deserialized_doc.get_multi_modal_attribute('image') + titles = doc.get_multi_modal_attribute('title') + + assert images[0].tensor.shape == (10, 10, 3) + assert titles[0].text == 'hello world' + assert 'multi_modal_schema' in deserialized_doc._metadata expected_schema = [ @@ -491,8 +497,10 @@ class MMDocument: ] _assert_doc_schema(deserialized_doc, expected_schema) - translated_obj = MMDocument(doc) - assert translated_obj == obj + translated_obj = MMDocument(deserialized_doc) + assert (translated_obj.image == obj.image).all() + assert translated_obj.title == obj.title + assert translated_obj.version == obj.version def test_json_type():
Multi-modal Document has a float position I created a `@dataclass` with a custom field for holding a collection of images with 2 embeddings each. Since it is better to wrap the image collection with a document, I have started the following modeling: ```python from typing import TypeVar, List from docarray import dataclass, field, Document from docarray.typing import Image, Text, JSON TrialImages = TypeVar('TrialImages', bound=str) def trial_images_setter(value: List[str]) -> Document: # TODO: this is still not a multi-modal document, but I think it is fine for now doc = Document(modality='trial_images') doc.chunks = [Document(uri=uri, modality='image').load_uri_to_image_tensor() for uri in value] return doc def trial_images_getter(doc: Document) -> List[str]: return [d.uri for d in doc.chunks] @dataclass class Lipstick: brand: Text color: Text nickname: Text meta: JSON product_image: Image # nested document for embeddings of skin and lip colors from all the trials trial_images: TrialImages = field(setter=trial_images_setter, getter=trial_images_getter, default_factory=[]) ``` While this is good, I wasn't able to get the `trial_images` from the `DocumentArray`. Document Summary & Error Log: ``` 📄 Document: 6ec9e9fe6ea097253cedcb8b938a303f └── 💠 Chunks ├── 📄 Document: 4ef01f5798e058fa9b4df48791414c20 │ ╭──────────────────────┬───────────────────────────────────────────────────────╮ │ │ Attribute │ Value │ │ ├──────────────────────┼───────────────────────────────────────────────────────┤ │ │ parent_id │ 6ec9e9fe6ea097253cedcb8b938a303f │ │ │ granularity │ 1 │ │ │ text │ MAC │ │ │ modality │ text │ │ ╰──────────────────────┴───────────────────────────────────────────────────────╯ ├── 📄 Document: 112c0f846fc7d2133ca92e21e675ae6b │ ╭──────────────────────┬───────────────────────────────────────────────────────╮ │ │ Attribute │ Value │ │ ├──────────────────────┼───────────────────────────────────────────────────────┤ │ │ parent_id │ 6ec9e9fe6ea097253cedcb8b938a303f │ │ │ granularity │ 1 │ │ │ text │ Marrakesh │ │ │ modality │ text │ │ ╰──────────────────────┴───────────────────────────────────────────────────────╯ ├── 📄 Document: 7d35324e75a8a4d0af507b90d733584d │ ╭──────────────────────┬───────────────────────────────────────────────────────╮ │ │ Attribute │ Value │ │ ├──────────────────────┼───────────────────────────────────────────────────────┤ │ │ parent_id │ 6ec9e9fe6ea097253cedcb8b938a303f │ │ │ granularity │ 1 │ │ │ text │ 麻辣鸡丝 │ │ │ modality │ text │ │ ╰──────────────────────┴───────────────────────────────────────────────────────╯ ├── 📄 Document: f2105af51c6b56f7b1a8bd2af94e28fe │ ╭──────────────────────┬───────────────────────────────────────────────────────╮ │ │ Attribute │ Value │ │ ├──────────────────────┼───────────────────────────────────────────────────────┤ │ │ parent_id │ 6ec9e9fe6ea097253cedcb8b938a303f │ │ │ granularity │ 1 │ │ │ tags │ {'type': ['口红', '哑光']} │ │ │ modality │ json │ │ ╰──────────────────────┴───────────────────────────────────────────────────────╯ ├── 📄 Document: 42b6effc1ed1fe7c75c907b212d0e63d │ ╭─────────────┬────────────────────────────────────────────────────────────────╮ │ │ Attribute │ Value │ │ ├─────────────┼────────────────────────────────────────────────────────────────┤ │ │ parent_id │ 6ec9e9fe6ea097253cedcb8b938a303f │ │ │ granularity │ 1 │ │ │ tensor │ <class 'numpy.ndarray'> in shape (600, 640, 3), dtype: uint8 │ │ │ uri │ https://s1.vika.cn/space/2022/06/08/3709d7793d964e5393bcabfc9… │ │ │ modality │ image │ │ ╰─────────────┴────────────────────────────────────────────────────────────────╯ └── 📄 Document: 80dd7ee3fd6a6b9c258baf714376b937 ╭──────────────────────┬───────────────────────────────────────────────────────╮ │ Attribute │ Value │ ├──────────────────────┼───────────────────────────────────────────────────────┤ │ parent_id │ 6ec9e9fe6ea097253cedcb8b938a303f │ │ granularity │ 1 │ │ modality │ trial_images │ ╰──────────────────────┴───────────────────────────────────────────────────────╯ └── 💠 Chunks ├── 📄 Document: e2ff2813f6e7e5eebefdb95b241db382 │ ╭─────────────┬────────────────────────────────────────────────────────────────╮ │ │ Attribute │ Value │ │ ├─────────────┼────────────────────────────────────────────────────────────────┤ │ │ parent_id │ 80dd7ee3fd6a6b9c258baf714376b937 │ │ │ granularity │ 1 │ │ │ tensor │ <class 'numpy.ndarray'> in shape (283, 175, 3), dtype: uint8 │ │ │ uri │ https://s1.vika.cn/space/2022/06/08/7f3680ba48114ebeba83b2938… │ │ │ modality │ image │ │ ╰─────────────┴────────────────────────────────────────────────────────────────╯ ├── 📄 Document: 27e552e852f86eb8d349a213c1d87755 │ ╭─────────────┬────────────────────────────────────────────────────────────────╮ │ │ Attribute │ Value │ │ ├─────────────┼────────────────────────────────────────────────────────────────┤ │ │ parent_id │ 80dd7ee3fd6a6b9c258baf714376b937 │ │ │ granularity │ 1 │ │ │ tensor │ <class 'numpy.ndarray'> in shape (260, 146, 3), dtype: uint8 │ │ │ uri │ https://s1.vika.cn/space/2022/06/08/5577cf7ebfa6459eafa0c2cd9… │ │ │ modality │ image │ │ ╰─────────────┴────────────────────────────────────────────────────────────────╯ ├── 📄 Document: 88294367d4ed0dd3019909e9a55350dd │ ╭─────────────┬────────────────────────────────────────────────────────────────╮ │ │ Attribute │ Value │ │ ├─────────────┼────────────────────────────────────────────────────────────────┤ │ │ parent_id │ 80dd7ee3fd6a6b9c258baf714376b937 │ │ │ granularity │ 1 │ │ │ tensor │ <class 'numpy.ndarray'> in shape (606, 1075, 3), dtype: uint8 │ │ │ uri │ https://s1.vika.cn/space/2022/06/08/104b47a6afec4ef68472747ef… │ │ │ modality │ image │ │ ╰─────────────┴────────────────────────────────────────────────────────────────╯ └── 📄 Document: c721a22350a76e73952ccba0a5cf9e82 ╭─────────────┬────────────────────────────────────────────────────────────────╮ │ Attribute │ Value │ ├─────────────┼────────────────────────────────────────────────────────────────┤ │ parent_id │ 80dd7ee3fd6a6b9c258baf714376b937 │ │ granularity │ 1 │ │ tensor │ <class 'numpy.ndarray'> in shape (602, 1076, 3), dtype: uint8 │ │ uri │ https://s1.vika.cn/space/2022/06/08/b16b5bf313294cbeb1434bc5d… │ │ modality │ image │ ╰─────────────┴────────────────────────────────────────────────────────────────╯ ╭───────────────────── Documents Summary ─────────────────────╮ │ │ │ Length 1 │ │ Homogenous Documents True │ │ Has nested Documents in ('chunks',) │ │ Common Attributes ('id', 'embedding', 'chunks') │ │ Multimodal dataclass True │ │ │ ╰─────────────────────────────────────────────────────────────╯ ╭──────────────────────── Attributes Summary ────────────────────────╮ │ │ │ Attribute Data type #Unique values Has empty value │ │ ──────────────────────────────────────────────────────────────── │ │ chunks ('ChunkArray',) 1 False │ │ embedding ('ndarray',) 1 False │ │ id ('str',) 1 False │ │ │ ╰────────────────────────────────────────────────────────────────────╯ ╭─ DocumentArrayAnnlite Config ─╮ │ │ │ n_dim 50 │ │ metric cosine │ │ serialize_config {} │ │ data_path ./data │ │ ef_construction None │ │ ef_search None │ │ max_connection None │ │ columns [] │ │ │ ╰───────────────────────────────╯ ⠹ Working... ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0:00:00 0% ETA: -:--:-- ERROR lipstickTrialImageExecutor/rep-0@89864 IndexError('Unsupported index type builtins.float: 5.0') [06/09/22 12:10:58] add "--quiet-error" to suppress the exception details ╭─────────────────────────────────────────────────── Traceback (most recent call last) ────────────────────────────────────────────────────╮ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/jina/serve/runtimes/worker/__init__.py:162 in │ │ process_data │ │ │ │ 159 │ │ │ │ if self.logger.debug_enabled: │ │ 160 │ │ │ │ │ self._log_data_request(requests[0]) │ │ 161 │ │ │ │ │ │ ❱ 162 │ │ │ │ return await self._data_request_handler.handle(requests=requests) │ │ 163 │ │ │ except (RuntimeError, Exception) as ex: │ │ 164 │ │ │ │ self.logger.error( │ │ 165 │ │ │ │ │ f'{ex!r}' │ │ │ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/jina/serve/runtimes/request_handlers/data_reques… │ │ in handle │ │ │ │ 147 │ │ ) │ │ 148 │ │ │ │ 149 │ │ # executor logic │ │ ❱ 150 │ │ return_data = await self._executor.__acall__( │ │ 151 │ │ │ req_endpoint=requests[0].header.exec_endpoint, │ │ 152 │ │ │ docs=docs, │ │ 153 │ │ │ parameters=params, │ │ │ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/jina/serve/executors/__init__.py:272 in __acall__ │ │ │ │ 269 │ │ # noqa: DAR201 │ │ 270 │ │ """ │ │ 271 │ │ if req_endpoint in self.requests: │ │ ❱ 272 │ │ │ return await self.__acall_endpoint__(req_endpoint, **kwargs) │ │ 273 │ │ elif __default_endpoint__ in self.requests: │ │ 274 │ │ │ return await self.__acall_endpoint__(__default_endpoint__, **kwargs) │ │ 275 │ │ │ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/jina/serve/executors/__init__.py:295 in │ │ __acall_endpoint__ │ │ │ │ 292 │ │ │ if iscoroutinefunction(func): │ │ 293 │ │ │ │ return await func(self, **kwargs) │ │ 294 │ │ │ else: │ │ ❱ 295 │ │ │ │ return func(self, **kwargs) │ │ 296 │ │ │ 297 │ @property │ │ 298 │ def workspace(self) -> Optional[str]: │ │ │ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/jina/serve/executors/decorators.py:180 in │ │ arg_wrapper │ │ │ │ 177 │ │ │ │ def arg_wrapper( │ │ 178 │ │ │ │ │ executor_instance, *args, **kwargs │ │ 179 │ │ │ │ ): # we need to get the summary from the executor, so we need to access │ │ the self │ │ ❱ 180 │ │ │ │ │ return fn(executor_instance, *args, **kwargs) │ │ 181 │ │ │ │ │ │ 182 │ │ │ │ self.fn = arg_wrapper │ │ 183 │ │ │ │ /Users/simon/Documents/git-repo/cool/lipstick-db/executor.py:46 in index │ │ │ │ 43 class LipstickTrialImageExecutor(Executor): │ │ 44 │ @requests(on='/index') │ │ 45 │ def index(self, docs: DocumentArray, **kwargs): │ │ ❱ 46 │ │ trial_images = docs['@.[trial_images]c'] │ │ 47 │ │ return trial_images │ │ 48 │ │ │ 49 │ def _get_face_mesh(self, img_rgb): │ │ │ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/docarray/array/mixins/getitem.py:55 in │ │ __getitem__ │ │ │ │ 52 │ │ │ return self._get_doc_by_offset(int(index)) │ │ 53 │ │ elif isinstance(index, str): │ │ 54 │ │ │ if index.startswith('@'): │ │ ❱ 55 │ │ │ │ return self.traverse_flat(index[1:]) │ │ 56 │ │ │ else: │ │ 57 │ │ │ │ return self._get_doc_by_id(index) │ │ 58 │ │ elif isinstance(index, slice): │ │ │ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/docarray/array/mixins/traverse.py:195 in │ │ traverse_flat │ │ │ │ 192 │ │ │ return self │ │ 193 │ │ │ │ 194 │ │ leaves = self.traverse(traversal_paths, filter_fn=filter_fn) │ │ ❱ 195 │ │ return self._flatten(leaves) │ │ 196 │ │ │ 197 │ def flatten(self) -> 'DocumentArray': │ │ 198 │ │ """Flatten all nested chunks and matches into one :class:`DocumentArray`. │ │ │ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/docarray/array/mixins/traverse.py:234 in _flatten │ │ │ │ 231 │ def _flatten(sequence) -> 'DocumentArray': │ │ 232 │ │ from ... import DocumentArray │ │ 233 │ │ │ │ ❱ 234 │ │ return DocumentArray(list(itertools.chain.from_iterable(sequence))) │ │ 235 │ │ 236 │ │ 237 def _parse_path_string(p: str) -> Dict[str, str]: │ │ │ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/docarray/array/mixins/traverse.py:108 in traverse │ │ │ │ 105 │ │ """ │ │ 106 │ │ traversal_paths = re.sub(r'\s+', '', traversal_paths) │ │ 107 │ │ for p in _re_traversal_path_split(traversal_paths): │ │ ❱ 108 │ │ │ yield from self._traverse(self, p, filter_fn=filter_fn) │ │ 109 │ │ │ 110 │ @staticmethod │ │ 111 │ def _traverse( │ │ │ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/docarray/array/mixins/traverse.py:141 in │ │ _traverse │ │ │ │ 138 │ │ │ │ for d in docs: │ │ 139 │ │ │ │ │ for attribute in group_dict['attributes']: │ │ 140 │ │ │ │ │ │ yield from TraverseMixin._traverse( │ │ ❱ 141 │ │ │ │ │ │ │ d.get_multi_modal_attribute(attribute)[cur_slice], │ │ 142 │ │ │ │ │ │ │ remainder, │ │ 143 │ │ │ │ │ │ │ filter_fn=filter_fn, │ │ 144 │ │ │ │ │ │ ) │ │ │ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/docarray/document/mixins/multimodal.py:119 in │ │ get_multi_modal_attribute │ │ │ │ 116 │ │ position = self._metadata['multi_modal_schema'][attribute].get('position') │ │ 117 │ │ │ │ 118 │ │ if attribute_type in [AttributeType.DOCUMENT, AttributeType.NESTED]: │ │ ❱ 119 │ │ │ return DocumentArray([self.chunks[position]]) │ │ 120 │ │ elif attribute_type in [ │ │ 121 │ │ │ AttributeType.ITERABLE_DOCUMENT, │ │ 122 │ │ │ AttributeType.ITERABLE_NESTED, │ │ │ │ /Users/simon/.local/share/virtualenvs/lipstick-db-nPH6fbgy/lib/python3.8/site-packages/docarray/array/mixins/getitem.py:108 in │ │ __getitem__ │ │ │ │ 105 │ │ │ │ raise IndexError( │ │ 106 │ │ │ │ │ f'When using np.ndarray as index, its `ndim` must =1. However, │ │ receiving ndim={index.ndim}' │ │ 107 │ │ │ │ ) │ │ ❱ 108 │ │ raise IndexError(f'Unsupported index type {typename(index)}: {index}') │ │ 109 │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ IndexError: Unsupported index type builtins.float: 5.0 ``` After checking the code, I found the position attribute of the `multi_modal_schema` is a `float`: ```python {'nickname': {'type': 'Text', 'attribute_type': 'document', 'position': 2.0}, 'product_image': {'position': 4.0, 'type': 'Image', 'attribute_type': 'document'}, 'trial_images': {'attribute_type': 'document', 'position': 5.0, 'type': 'TrialImages'}, 'brand': {'type': 'Text', 'attribute_type': 'document', 'position': 0.0}, 'meta': {'attribute_type': 'document', 'position': 3.0, 'type': 'JSON'}, 'color': {'position': 1.0, 'attribute_type': 'document', 'type': 'Text'}} ``` Not sure why the positions turn into floats, but I think we need to cast it to `int` at the time of retrieving it to be safe. Will provide a PR for a fix. Was able to verify in my repository that the fix works.
2022-06-09T04:20:01
docarray/docarray
979
docarray__docarray-979
[ "978" ]
1431b07c1f27f239b8c864681c77f886ddb7a174
diff --git a/docarray/typing/url/any_url.py b/docarray/typing/url/any_url.py --- a/docarray/typing/url/any_url.py +++ b/docarray/typing/url/any_url.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING, Type, TypeVar +from typing import TYPE_CHECKING, Optional, Type, TypeVar from pydantic import AnyUrl as BaseAnyUrl from pydantic import errors, parse_obj_as @@ -34,11 +34,14 @@ def validate_parts(cls, parts: 'Parts', validate_port: bool = True) -> 'Parts': """ A method used to validate parts of a URL. Our URLs should be able to function both in local and remote settings. - Therefore, we allow missing `scheme`, making it possible to pass a file path. + Therefore, we allow missing `scheme`, making it possible to pass a file + path without prefix. + If `scheme` is missing, we assume it is a local file path. """ scheme = parts['scheme'] if scheme is None: - pass # allow missing scheme, unlike pydantic + # allow missing scheme, unlike pydantic + pass elif cls.allowed_schemes and scheme.lower() not in cls.allowed_schemes: raise errors.UrlSchemePermittedError(set(cls.allowed_schemes)) @@ -52,6 +55,44 @@ def validate_parts(cls, parts: 'Parts', validate_port: bool = True) -> 'Parts': return parts + @classmethod + def build( + cls, + *, + scheme: str, + user: Optional[str] = None, + password: Optional[str] = None, + host: str, + port: Optional[str] = None, + path: Optional[str] = None, + query: Optional[str] = None, + fragment: Optional[str] = None, + **_kwargs: str, + ) -> str: + """ + Build a URL from its parts. + The only difference from the pydantic implementation is that we allow + missing `scheme`, making it possible to pass a file path without prefix. + """ + + # allow missing scheme, unlike pydantic + scheme_ = scheme if scheme is not None else '' + url = super().build( + scheme=scheme_, + user=user, + password=password, + host=host, + port=port, + path=path, + query=query, + fragment=fragment, + **_kwargs, + ) + if scheme is None and url.startswith('://'): + # remove the `://` prefix, since scheme is missing + url = url[3:] + return url + @classmethod def from_protobuf(cls: Type[T], pb_msg: 'str') -> T: """
diff --git a/tests/units/typing/url/test_any_url.py b/tests/units/typing/url/test_any_url.py --- a/tests/units/typing/url/test_any_url.py +++ b/tests/units/typing/url/test_any_url.py @@ -18,3 +18,9 @@ def test_json_schema(): def test_dump_json(): url = parse_obj_as(AnyUrl, 'http://jina.ai/img.png') orjson_dumps(url) + + +def test_relative_path(): + # see issue: https://github.com/docarray/docarray/issues/978 + url = parse_obj_as(AnyUrl, 'data/05978.jpg') + assert url == 'data/05978.jpg'
bug(v2): relative file paths in url types Passing relative file paths gives a validation error: ```python from docarray import Image url = 'Test/05978.jpg' img = Image(url=url) ``` ```text Test/05978.jpg Traceback (most recent call last): File "/home/johannes/.config/JetBrains/PyCharmCE2022.3/scratches/scratch_116.py", line 12, in <module> img = Image(url=url) File "pydantic/main.py", line 342, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for Image url unsupported operand type(s) for +: 'NoneType' and 'str' (type=type_error) ```
2023-01-03T14:07:57
docarray/docarray
991
docarray__docarray-991
[ "988" ]
1ac338f2940dc54588d54334943b1e0c407e4616
diff --git a/docarray/typing/tensor/abstract_tensor.py b/docarray/typing/tensor/abstract_tensor.py --- a/docarray/typing/tensor/abstract_tensor.py +++ b/docarray/typing/tensor/abstract_tensor.py @@ -15,9 +15,48 @@ ShapeT = TypeVar('ShapeT') +class _ParametrizedMeta(type): + """ + This metaclass ensures that instance and subclass checks on parametrized Tensors + are handled as expected: + + assert issubclass(TorchTensor[128], TorchTensor[128]) + t = parse_obj_as(TorchTensor[128], torch.zeros(128)) + assert isinstance(t, TorchTensor[128]) + etc. + + This special handling is needed because every call to `AbstractTensor.__getitem__` + creates a new class on the fly. + We want technically distinct but identical classes to be considered equal. + """ + + def __subclasscheck__(cls, subclass): + is_tensor = AbstractTensor in subclass.mro() + same_parents = is_tensor and cls.mro()[1:] == subclass.mro()[1:] + + subclass_target_shape = getattr(subclass, '__docarray_target_shape__', False) + self_target_shape = getattr(cls, '__docarray_target_shape__', False) + same_shape = ( + same_parents + and subclass_target_shape + and self_target_shape + and subclass_target_shape == self_target_shape + ) + + if same_shape: + return True + return super().__subclasscheck__(subclass) + + def __instancecheck__(cls, instance): + is_tensor = isinstance(instance, AbstractTensor) + if is_tensor: # custom handling + return any(issubclass(candidate, cls) for candidate in type(instance).mro()) + return super().__instancecheck__(instance) + + class AbstractTensor(Generic[ShapeT], AbstractType, ABC): - __parametrized_meta__ = type + __parametrized_meta__: type = _ParametrizedMeta _PROTO_FIELD_NAME: str @classmethod @@ -76,7 +115,7 @@ class _ParametrizedTensor( cls, # type: ignore metaclass=cls.__parametrized_meta__, # type: ignore ): - _docarray_target_shape = shape + __docarray_target_shape__ = shape @classmethod def validate( @@ -86,7 +125,9 @@ def validate( config: 'BaseConfig', ): t = super().validate(value, field, config) - return _cls.__docarray_validate_shape__(t, _cls._docarray_target_shape) + return _cls.__docarray_validate_shape__( + t, _cls.__docarray_target_shape__ + ) _ParametrizedTensor.__name__ = f'{cls.__name__}[{shape_str}]' _ParametrizedTensor.__qualname__ = f'{cls.__qualname__}[{shape_str}]' diff --git a/docarray/typing/tensor/ndarray.py b/docarray/typing/tensor/ndarray.py --- a/docarray/typing/tensor/ndarray.py +++ b/docarray/typing/tensor/ndarray.py @@ -23,9 +23,19 @@ from docarray.computation.numpy_backend import NumpyCompBackend from docarray.proto import NdArrayProto, NodeProto +from docarray.base_document.base_node import BaseNode + T = TypeVar('T', bound='NdArray') ShapeT = TypeVar('ShapeT') +tensor_base: type = type(BaseNode) + + +# the mypy error suppression below should not be necessary anymore once the following +# is released in mypy: https://github.com/python/mypy/pull/14135 +class metaNumpy(AbstractTensor.__parametrized_meta__, tensor_base): # type: ignore + pass + class NdArray(np.ndarray, AbstractTensor, Generic[ShapeT]): """ @@ -71,6 +81,7 @@ class MyDoc(BaseDocument): """ _PROTO_FIELD_NAME = 'ndarray' + __parametrized_meta__ = metaNumpy @classmethod def __get_validators__(cls): diff --git a/docarray/typing/tensor/torch_tensor.py b/docarray/typing/tensor/torch_tensor.py --- a/docarray/typing/tensor/torch_tensor.py +++ b/docarray/typing/tensor/torch_tensor.py @@ -19,11 +19,17 @@ T = TypeVar('T', bound='TorchTensor') ShapeT = TypeVar('ShapeT') -torch_base = type(torch.Tensor) # type: Any -node_base = type(BaseNode) # type: Any +torch_base: type = type(torch.Tensor) +node_base: type = type(BaseNode) -class metaTorchAndNode(torch_base, node_base): +# the mypy error suppression below should not be necessary anymore once the following +# is released in mypy: https://github.com/python/mypy/pull/14135 +class metaTorchAndNode( + AbstractTensor.__parametrized_meta__, # type: ignore + torch_base, # type: ignore + node_base, # type: ignore +): # type: ignore pass
diff --git a/tests/units/typing/tensor/test_tensor.py b/tests/units/typing/tensor/test_tensor.py --- a/tests/units/typing/tensor/test_tensor.py +++ b/tests/units/typing/tensor/test_tensor.py @@ -90,3 +90,39 @@ def test_np_embedding(): # illegal shape at class creation time with pytest.raises(ValueError): parse_obj_as(NdArrayEmbedding[128, 128], np.zeros((128, 128))) + + +def test_parametrized_subclass(): + c1 = NdArray[128] + c2 = NdArray[128] + assert issubclass(c1, c2) + assert issubclass(c1, NdArray) + assert issubclass(c1, np.ndarray) + + assert not issubclass(c1, NdArray[256]) + + +def test_parametrized_instance(): + t = parse_obj_as(NdArray[128], np.zeros(128)) + assert isinstance(t, NdArray[128]) + assert isinstance(t, NdArray) + assert isinstance(t, np.ndarray) + + assert not isinstance(t, NdArray[256]) + + +def test_parametrized_equality(): + t1 = parse_obj_as(NdArray[128], np.zeros(128)) + t2 = parse_obj_as(NdArray[128], np.zeros(128)) + t3 = parse_obj_as(NdArray[256], np.zeros(256)) + assert (t1 == t2).all() + assert not t1 == t3 + + +def test_parametrized_operations(): + t1 = parse_obj_as(NdArray[128], np.zeros(128)) + t2 = parse_obj_as(NdArray[128], np.zeros(128)) + t_result = t1 + t2 + assert isinstance(t_result, np.ndarray) + assert isinstance(t_result, NdArray) + assert isinstance(t_result, NdArray[128]) diff --git a/tests/units/typing/tensor/test_torch_tensor.py b/tests/units/typing/tensor/test_torch_tensor.py --- a/tests/units/typing/tensor/test_torch_tensor.py +++ b/tests/units/typing/tensor/test_torch_tensor.py @@ -82,3 +82,39 @@ def test_torch_embedding(): # illegal shape at class creation time with pytest.raises(ValueError): parse_obj_as(TorchEmbedding[128, 128], torch.zeros(128, 128)) + + +def test_parametrized_subclass(): + c1 = TorchTensor[128] + c2 = TorchTensor[128] + assert issubclass(c1, c2) + assert issubclass(c1, TorchTensor) + assert issubclass(c1, torch.Tensor) + + assert not issubclass(c1, TorchTensor[256]) + + +def test_parametrized_instance(): + t = parse_obj_as(TorchTensor[128], torch.zeros(128)) + assert isinstance(t, TorchTensor[128]) + assert isinstance(t, TorchTensor) + assert isinstance(t, torch.Tensor) + + assert not isinstance(t, TorchTensor[256]) + + +def test_parametrized_equality(): + t1 = parse_obj_as(TorchTensor[128], torch.zeros(128)) + t2 = parse_obj_as(TorchTensor[128], torch.zeros(128)) + t3 = parse_obj_as(TorchTensor[256], torch.zeros(256)) + assert (t1 == t2).all() + assert not t1 == t3 + + +def test_parametrized_operations(): + t1 = parse_obj_as(TorchTensor[128], torch.zeros(128)) + t2 = parse_obj_as(TorchTensor[128], torch.zeros(128)) + t_result = t1 + t2 + assert isinstance(t_result, torch.Tensor) + assert isinstance(t_result, TorchTensor) + assert isinstance(t_result, TorchTensor[128])
Bug: Shape info in tensor break forward in some pytorch op # Context with `TorchTensor[512]` this break in some case `as_expand` error ``` TypeError Traceback (most recent call last) Cell In[182], line 4 1 for i, batch in enumerate(loader): 2 #assert batch.image.tensor.shape == (2, 3, 224, 224) 3 print(model.encode_vision(batch.image).shape) ----> 4 print(model.encode_text(batch.text)) 6 break Cell In[176], line 12, in CLIP.encode_text(self, texts) 11 def encode_text(self, texts: Text) -> TorchTensor: ---> 12 return self.bert(input_ids = texts.tokens.input_ids, attention_mask = texts.tokens.attention_mask) File ~/.config/JetBrains/PyCharmCE2022.3/scratches/laion/venv/lib/python3.9/site-packages/torch/nn/modules/module.py:1194, in Module._call_impl(self, *input, **kwargs) 1190 # If we don't have any hooks, we want to skip the rest of the logic in 1191 # this function, and just call forward. 1192 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks 1193 or _global_forward_hooks or _global_forward_pre_hooks): -> 1194 return forward_call(*input, **kwargs) 1195 # Do not call functions when jit is used 1196 full_backward_hooks, non_full_backward_hooks = [], [] File ~/.config/JetBrains/PyCharmCE2022.3/scratches/laion/venv/lib/python3.9/site-packages/transformers/models/distilbert/modeling_distilbert.py:579, in DistilBertModel.forward(self, input_ids, attention_mask, head_mask, inputs_embeds, output_attentions, output_hidden_states, return_dict) 577 if inputs_embeds is None: 578 inputs_embeds = self.embeddings(input_ids) # (bs, seq_length, dim) --> 579 return self.transformer( 580 x=inputs_embeds, 581 attn_mask=attention_mask, 582 head_mask=head_mask, 583 output_attentions=output_attentions, 584 output_hidden_states=output_hidden_states, 585 return_dict=return_dict, 586 ) File ~/.config/JetBrains/PyCharmCE2022.3/scratches/laion/venv/lib/python3.9/site-packages/torch/nn/modules/module.py:1194, in Module._call_impl(self, *input, **kwargs) 1190 # If we don't have any hooks, we want to skip the rest of the logic in 1191 # this function, and just call forward. 1192 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks 1193 or _global_forward_hooks or _global_forward_pre_hooks): -> 1194 return forward_call(*input, **kwargs) 1195 # Do not call functions when jit is used 1196 full_backward_hooks, non_full_backward_hooks = [], [] File ~/.config/JetBrains/PyCharmCE2022.3/scratches/laion/venv/lib/python3.9/site-packages/transformers/models/distilbert/modeling_distilbert.py:354, in Transformer.forward(self, x, attn_mask, head_mask, output_attentions, output_hidden_states, return_dict) 351 if output_hidden_states: 352 all_hidden_states = all_hidden_states + (hidden_state,) --> 354 layer_outputs = layer_module( 355 x=hidden_state, attn_mask=attn_mask, head_mask=head_mask[i], output_attentions=output_attentions 356 ) 357 hidden_state = layer_outputs[-1] 359 if output_attentions: File ~/.config/JetBrains/PyCharmCE2022.3/scratches/laion/venv/lib/python3.9/site-packages/torch/nn/modules/module.py:1194, in Module._call_impl(self, *input, **kwargs) 1190 # If we don't have any hooks, we want to skip the rest of the logic in 1191 # this function, and just call forward. 1192 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks 1193 or _global_forward_hooks or _global_forward_pre_hooks): -> 1194 return forward_call(*input, **kwargs) 1195 # Do not call functions when jit is used 1196 full_backward_hooks, non_full_backward_hooks = [], [] File ~/.config/JetBrains/PyCharmCE2022.3/scratches/laion/venv/lib/python3.9/site-packages/transformers/models/distilbert/modeling_distilbert.py:289, in TransformerBlock.forward(self, x, attn_mask, head_mask, output_attentions) 279 """ 280 Parameters: 281 x: torch.tensor(bs, seq_length, dim) (...) 286 torch.tensor(bs, seq_length, dim) The output of the transformer block contextualization. 287 """ 288 # Self-Attention --> 289 sa_output = self.attention( 290 query=x, 291 key=x, 292 value=x, 293 mask=attn_mask, 294 head_mask=head_mask, 295 output_attentions=output_attentions, 296 ) 297 if output_attentions: 298 sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length) File ~/.config/JetBrains/PyCharmCE2022.3/scratches/laion/venv/lib/python3.9/site-packages/torch/nn/modules/module.py:1194, in Module._call_impl(self, *input, **kwargs) 1190 # If we don't have any hooks, we want to skip the rest of the logic in 1191 # this function, and just call forward. 1192 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks 1193 or _global_forward_hooks or _global_forward_pre_hooks): -> 1194 return forward_call(*input, **kwargs) 1195 # Do not call functions when jit is used 1196 full_backward_hooks, non_full_backward_hooks = [], [] File ~/.config/JetBrains/PyCharmCE2022.3/scratches/laion/venv/lib/python3.9/site-packages/transformers/models/distilbert/modeling_distilbert.py:215, in MultiHeadSelfAttention.forward(self, query, key, value, mask, head_mask, output_attentions) 213 q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head) 214 scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, q_length, k_length) --> 215 mask = (mask == 0).view(mask_reshp).expand_as(scores) # (bs, n_heads, q_length, k_length) 216 scores = scores.masked_fill( 217 mask, torch.tensor(torch.finfo(scores.dtype).min) 218 ) # (bs, n_heads, q_length, k_length) 220 weights = nn.functional.softmax(scores, dim=-1) # (bs, n_heads, q_length, k_length) TypeError: no implementation found for 'torch.Tensor.expand_as' on types that implement __torch_function__: [<class 'docarray.typing.tensor.abstract_tensor.TorchTensor[512]'>, <class 'docarray.typing.tensor.abstract_tensor.TorchTensor[512]'>] ```
2023-01-05T13:31:03
docarray/docarray
1,094
docarray__docarray-1094
[ "1085" ]
de8f70e574122d39a0f0cd5a781fe4a252e4ea51
diff --git a/docarray/array/array_stacked.py b/docarray/array/array_stacked.py --- a/docarray/array/array_stacked.py +++ b/docarray/array/array_stacked.py @@ -171,7 +171,18 @@ def _create_columns( val = tensor_type.get_comp_backend().none_value() cast(AbstractTensor, tensor_columns[field])[i] = val - setattr(doc, field, tensor_columns[field][i]) + + # If the stacked tensor is rank 1, the individual tensors are + # rank 0 (scalar) + # This is problematic because indexing a rank 1 tensor in numpy + # returns a value instead of a tensor + # We thus chose to convert the individual rank 0 tensors to rank 1 + # This does mean that stacking rank 0 tensors will transform them + # to rank 1 + if tensor_columns[field].ndim == 1: + setattr(doc, field, tensor_columns[field][i : i + 1]) + else: + setattr(doc, field, tensor_columns[field][i]) del val elif issubclass(type_, BaseDocument): diff --git a/docarray/typing/tensor/abstract_tensor.py b/docarray/typing/tensor/abstract_tensor.py --- a/docarray/typing/tensor/abstract_tensor.py +++ b/docarray/typing/tensor/abstract_tensor.py @@ -265,3 +265,9 @@ def _docarray_to_json_compatible(self): :return: a representation of the tensor compatible with orjson """ ... + + @property + @abc.abstractmethod + def ndim(self) -> int: + """The number of dimensions / rank of this tensor.""" + ...
diff --git a/tests/units/array/test_array_stacked.py b/tests/units/array/test_array_stacked.py --- a/tests/units/array/test_array_stacked.py +++ b/tests/units/array/test_array_stacked.py @@ -365,3 +365,86 @@ class MyDoc(BaseDocument): da = da.stack() assert da[0].tensor.dtype == np.int32 assert da.tensor.dtype == np.int32 + + +def test_np_scalar(): + class MyDoc(BaseDocument): + scalar: NdArray + + da = DocumentArray[MyDoc]( + [MyDoc(scalar=np.array(2.0)) for _ in range(3)], tensor_type=NdArray + ) + assert all(doc.scalar.ndim == 0 for doc in da) + assert all(doc.scalar == 2.0 for doc in da) + + stacked_da = da.stack() + assert type(stacked_da.scalar) == NdArray + + assert all(type(doc.scalar) == NdArray for doc in da) + assert all(doc.scalar.ndim == 1 for doc in da) + assert all(doc.scalar == 2.0 for doc in da) + + # Make sure they share memory + stacked_da.scalar[0] = 3.0 + assert da[0].scalar == 3.0 + + +def test_torch_scalar(): + class MyDoc(BaseDocument): + scalar: TorchTensor + + da = DocumentArray[MyDoc]( + [MyDoc(scalar=torch.tensor(2.0)) for _ in range(3)], tensor_type=TorchTensor + ) + assert all(doc.scalar.ndim == 0 for doc in da) + assert all(doc.scalar == 2.0 for doc in da) + stacked_da = da.stack() + assert type(stacked_da.scalar) == TorchTensor + + assert all(type(doc.scalar) == TorchTensor for doc in da) + assert all(doc.scalar.ndim == 1 for doc in da) + assert all(doc.scalar == 2.0 for doc in da) + + # Make sure they share memory + stacked_da.scalar[0] = 3.0 + assert da[0].scalar == 3.0 + + +def test_np_nan(): + class MyDoc(BaseDocument): + scalar: Optional[NdArray] + + da = DocumentArray[MyDoc]([MyDoc() for _ in range(3)], tensor_type=NdArray) + assert all(doc.scalar is None for doc in da) + assert all(doc.scalar == doc.scalar for doc in da) + stacked_da = da.stack() + assert type(stacked_da.scalar) == NdArray + + assert all(type(doc.scalar) == NdArray for doc in da) + # Stacking them turns them into np.nan + assert all(doc.scalar.ndim == 1 for doc in da) + assert all(doc.scalar != doc.scalar for doc in da) # Test for nan + + # Make sure they share memory + stacked_da.scalar[0] = 3.0 + assert da[0].scalar == 3.0 + + +def test_torch_nan(): + class MyDoc(BaseDocument): + scalar: Optional[TorchTensor] + + da = DocumentArray[MyDoc]([MyDoc() for _ in range(3)], tensor_type=TorchTensor) + assert all(doc.scalar is None for doc in da) + assert all(doc.scalar == doc.scalar for doc in da) + stacked_da = da.stack() + assert type(stacked_da.scalar) == TorchTensor + + assert all(type(doc.scalar) == TorchTensor for doc in da) + # Stacking them turns them into torch.nan + assert all(doc.scalar.ndim == 1 for doc in da) + assert all(doc.scalar != doc.scalar for doc in da) # Test for nan + + # Make sure they share memory + stacked_da.scalar[0] = 3.0 + assert da[0].scalar == 3.0
Document Array of `Image`s cannot be stacked twice when tensor_type=NdArray **Describe the bug** Document Array of Images cannot be stacked twice **To Reproduce** script.py ```python from docarray import DocumentArray from docarray.documents import Image BATCH_SIZE: int = 1024 da_image: DocumentArray[Image] = DocumentArray[Image]([Image() for _ in range(BATCH_SIZE)]) print("Stacking once") da_image.stack() print("Stacking twice") da_image.stack() print("Done!") ``` Output ```console Stacking once Stacking twice Traceback (most recent call last): File "rabbit.py", line 12, in <module> da_image.stack() File "/home/jackmin/Documents/da-testing/docarray/docarray/array/array.py", line 204, in stack return DocumentArrayStacked.__class_getitem__(self.document_type)(self) File "/home/jackmin/Documents/da-testing/docarray/docarray/array/array_stacked.py", line 66, in __init__ self.from_document_array(docs) File "/home/jackmin/Documents/da-testing/docarray/docarray/array/array_stacked.py", line 71, in from_document_array self._columns = self._create_columns(docs, tensor_type=self.tensor_type) File "/home/jackmin/Documents/da-testing/docarray/docarray/array/array_stacked.py", line 150, in _create_columns type_.get_comp_backend().empty( File "/home/jackmin/Documents/da-testing/docarray/docarray/computation/numpy_backend.py", line 75, in empty raise NotImplementedError('Numpy does not support devices (GPU).') NotImplementedError: Numpy does not support devices (GPU). ``` **Expected behavior** ```console Stacking once Stacking twice Done! ```
2023-02-07T15:31:09
docarray/docarray
1,367
docarray__docarray-1367
[ "1210" ]
7956a7c2070640f11c69fea6bf6f2acfd51fc372
diff --git a/docarray/index/abstract.py b/docarray/index/abstract.py --- a/docarray/index/abstract.py +++ b/docarray/index/abstract.py @@ -49,12 +49,12 @@ class FindResultBatched(NamedTuple): documents: List[DocList] - scores: np.ndarray + scores: List[np.ndarray] class _FindResultBatched(NamedTuple): documents: Union[List[DocList], List[List[Dict[str, Any]]]] - scores: np.ndarray + scores: List[np.ndarray] def _raise_not_composable(name): @@ -571,7 +571,9 @@ def text_search_batched( if len(da_list) > 0 and isinstance(da_list[0], List): docs = [self._dict_list_to_docarray(docs) for docs in da_list] - return FindResultBatched(documents=docs, scores=scores) + return FindResultBatched(documents=docs, scores=scores) + + return FindResultBatched(documents=da_list, scores=scores) ########################################################## # Helper methods # diff --git a/docarray/index/backends/weaviate.py b/docarray/index/backends/weaviate.py new file mode 100644 --- /dev/null +++ b/docarray/index/backends/weaviate.py @@ -0,0 +1,833 @@ +import base64 +import copy +import logging +import os +from dataclasses import dataclass, field +from pathlib import Path +from typing import ( + Any, + Dict, + Generator, + Generic, + List, + Optional, + Sequence, + Tuple, + Type, + TypeVar, + Union, + cast, +) + +import numpy as np +import weaviate +from pydantic import parse_obj_as +from typing_extensions import Literal + +import docarray +from docarray import BaseDoc, DocList +from docarray.index.abstract import BaseDocIndex, FindResultBatched, _FindResultBatched +from docarray.typing import AnyTensor +from docarray.typing.tensor.abstract_tensor import AbstractTensor +from docarray.typing.tensor.ndarray import NdArray +from docarray.utils.find import FindResult, _FindResult + +TSchema = TypeVar('TSchema', bound=BaseDoc) +T = TypeVar('T', bound='WeaviateDocumentIndex') + + +DEFAULT_BATCH_CONFIG = { + "batch_size": 20, + "dynamic": False, + "timeout_retries": 3, + "num_workers": 1, +} + +DEFAULT_BINARY_PATH = str(Path.home() / ".cache/weaviate-embedded/") +DEFAULT_PERSISTENCE_DATA_PATH = str(Path.home() / ".local/share/weaviate") + + +@dataclass +class EmbeddedOptions: + persistence_data_path: str = os.environ.get( + "XDG_DATA_HOME", DEFAULT_PERSISTENCE_DATA_PATH + ) + binary_path: str = os.environ.get("XDG_CACHE_HOME", DEFAULT_BINARY_PATH) + version: str = "latest" + port: int = 6666 + hostname: str = "127.0.0.1" + additional_env_vars: Optional[Dict[str, str]] = None + + +# TODO: add more types and figure out how to handle text vs string type +# see https://weaviate.io/developers/weaviate/configuration/datatypes +WEAVIATE_PY_VEC_TYPES = [list, np.ndarray, AbstractTensor] +WEAVIATE_PY_TYPES = [bool, int, float, str, docarray.typing.ID] + +# "id" and "_id" are reserved names in weaviate so we need to use a different +# name for the id column in a BaseDocument +DOCUMENTID = "docarrayid" + + +class WeaviateDocumentIndex(BaseDocIndex, Generic[TSchema]): + def __init__(self, db_config=None, **kwargs) -> None: + self.embedding_column: Optional[str] = None + self.properties: Optional[List[str]] = None + # keep track of the column name that contains the bytes + # type because we will store them as a base64 encoded string + # in weaviate + self.bytes_columns: List[str] = [] + # keep track of the array columns that are not embeddings because we will + # convert them to python lists before uploading to weaviate + self.nonembedding_array_columns: List[str] = [] + super().__init__(db_config=db_config, **kwargs) + self._db_config: WeaviateDocumentIndex.DBConfig = cast( + WeaviateDocumentIndex.DBConfig, self._db_config + ) + self._runtime_config: WeaviateDocumentIndex.RuntimeConfig = cast( + WeaviateDocumentIndex.RuntimeConfig, self._runtime_config + ) + + if self._db_config.embedded_options: + self._client = weaviate.Client( + embedded_options=self._db_config.embedded_options + ) + else: + self._client = weaviate.Client( + self._db_config.host, auth_client_secret=self._build_auth_credentials() + ) + + self._configure_client() + self._validate_columns() + self._set_embedding_column() + self._set_properties() + self._create_schema() + + def _set_properties(self) -> None: + field_overwrites = {"id": DOCUMENTID} + + self.properties = [ + field_overwrites.get(k, k) + for k, v in self._column_infos.items() + if v.config.get('is_embedding', False) is False + ] + + def _validate_columns(self) -> None: + # must have at most one column with property is_embedding=True + # and that column must be of type WEAVIATE_PY_VEC_TYPES + # TODO: update when https://github.com/weaviate/weaviate/issues/2424 + # is implemented and discuss best interface to signal which column(s) + # should be used for embeddings + num_embedding_columns = 0 + + for column_name, column_info in self._column_infos.items(): + if column_info.config.get('is_embedding', False): + num_embedding_columns += 1 + # if db_type is not 'number[]', then that means the type of the column in + # the given schema is not one of WEAVIATE_PY_VEC_TYPES + # note: the mapping between a column's type in the schema to a weaviate type + # is handled by the python_type_to_db_type method + if column_info.db_type != 'number[]': + raise ValueError( + f'Column {column_name} is marked as embedding but is not of type {WEAVIATE_PY_VEC_TYPES}' + ) + + if num_embedding_columns > 1: + raise ValueError( + f'Only one column can be marked as embedding but found {num_embedding_columns} columns marked as embedding' + ) + + def _set_embedding_column(self) -> None: + for column_name, column_info in self._column_infos.items(): + if column_info.config.get('is_embedding', False): + self.embedding_column = column_name + break + + def _configure_client(self) -> None: + self._client.batch.configure(**self._runtime_config.batch_config) + + def _build_auth_credentials(self): + dbconfig = self._db_config + + if dbconfig.auth_api_key: + return weaviate.auth.AuthApiKey(api_key=dbconfig.auth_api_key) + elif dbconfig.username and dbconfig.password: + return weaviate.auth.AuthClientPassword( + dbconfig.username, dbconfig.password, dbconfig.scopes + ) + else: + return None + + def configure(self, runtime_config=None, **kwargs) -> None: + super().configure(runtime_config, **kwargs) + self._configure_client() + + def _create_schema(self) -> None: + schema: Dict[str, Any] = {} + + properties = [] + column_infos = self._column_infos + + for column_name, column_info in column_infos.items(): + # in weaviate, we do not create a property for the doc's embeddings + if column_name == self.embedding_column: + continue + if column_info.db_type == 'blob': + self.bytes_columns.append(column_name) + if column_info.db_type == 'number[]': + self.nonembedding_array_columns.append(column_name) + prop = { + "name": column_name + if column_name != 'id' + else DOCUMENTID, # in weaviate, id and _id is a reserved keyword + "dataType": [column_info.db_type], + } + properties.append(prop) + + # TODO: What is the best way to specify other config that is part of schema? + # e.g. invertedIndexConfig, shardingConfig, moduleConfig, vectorIndexConfig + # and configure replication + # we will update base on user feedback + schema["properties"] = properties + schema["class"] = self._db_config.index_name + + # TODO: Use exists() instead of contains() when available + # see https://github.com/weaviate/weaviate-python-client/issues/232 + if self._client.schema.contains(schema): + logging.warning( + f"Found index {self._db_config.index_name} with schema {schema}. Will reuse existing schema." + ) + else: + self._client.schema.create_class(schema) + + @dataclass + class DBConfig(BaseDocIndex.DBConfig): + host: str = 'http://localhost:8080' + index_name: str = 'Document' + username: Optional[str] = None + password: Optional[str] = None + scopes: List[str] = field(default_factory=lambda: ["offline_access"]) + auth_api_key: Optional[str] = None + embedded_options: Optional[EmbeddedOptions] = None + + @dataclass + class RuntimeConfig(BaseDocIndex.RuntimeConfig): + default_column_config: Dict[Any, Dict[str, Any]] = field( + default_factory=lambda: { + np.ndarray: {}, + docarray.typing.ID: {}, + 'string': {}, + 'text': {}, + 'int': {}, + 'number': {}, + 'boolean': {}, + 'number[]': {}, + 'blob': {}, + } + ) + + batch_config: Dict[str, Any] = field( + default_factory=lambda: DEFAULT_BATCH_CONFIG + ) + + def _del_items(self, doc_ids: Sequence[str]): + has_matches = True + + operands = [ + {"path": [DOCUMENTID], "operator": "Equal", "valueString": doc_id} + for doc_id in doc_ids + ] + where_filter = { + "operator": "Or", + "operands": operands, + } + + # do a loop because there is a limit to how many objects can be deleted at + # in a single query + # see: https://weaviate.io/developers/weaviate/api/rest/batch#maximum-number-of-deletes-per-query + while has_matches: + results = self._client.batch.delete_objects( + class_name=self._db_config.index_name, + where=where_filter, + ) + + has_matches = results["results"]["matches"] + + def _filter(self, filter_query: Any, limit: int) -> Union[DocList, List[Dict]]: + self._overwrite_id(filter_query) + + results = ( + self._client.query.get(self._db_config.index_name, self.properties) + .with_additional("vector") + .with_where(filter_query) + .with_limit(limit) + .do() + ) + + docs = results["data"]["Get"][self._db_config.index_name] + + return [self._parse_weaviate_result(doc) for doc in docs] + + def _filter_batched( + self, filter_queries: Any, limit: int + ) -> Union[List[DocList], List[List[Dict]]]: + for filter_query in filter_queries: + self._overwrite_id(filter_query) + + qs = [ + self._client.query.get(self._db_config.index_name, self.properties) + .with_additional("vector") + .with_where(filter_query) + .with_limit(limit) + .with_alias(f'query_{i}') + for i, filter_query in enumerate(filter_queries) + ] + + batched_results = self._client.query.multi_get(qs).do() + + return [ + [self._parse_weaviate_result(doc) for doc in batched_result] + for batched_result in batched_results["data"]["Get"].values() + ] + + def find( + self, + query: Union[AnyTensor, BaseDoc], + search_field: str = '', + limit: int = 10, + **kwargs, + ): + self._logger.debug('Executing `find`') + if search_field != '': + raise ValueError( + 'Argument search_field is not supported for WeaviateDocumentIndex.\nSet search_field to an empty string to proceed.' + ) + embedding_field = self._get_embedding_field() + if isinstance(query, BaseDoc): + query_vec = self._get_values_by_column([query], embedding_field)[0] + else: + query_vec = query + query_vec_np = self._to_numpy(query_vec) + docs, scores = self._find( + query_vec_np, search_field=search_field, limit=limit, **kwargs + ) + + if isinstance(docs, List): + docs = self._dict_list_to_docarray(docs) + + return FindResult(documents=docs, scores=scores) + + def _overwrite_id(self, where_filter): + """ + Overwrite the id field in the where filter to DOCUMENTID + if the "id" field is present in the path + """ + for key, value in where_filter.items(): + if key == "path" and value == ["id"]: + where_filter[key] = [DOCUMENTID] + elif isinstance(value, dict): + self._overwrite_id(value) + elif isinstance(value, list): + for item in value: + if isinstance(item, dict): + self._overwrite_id(item) + + def _find( + self, + query: np.ndarray, + limit: int, + search_field: str = '', + score_name: Literal["certainty", "distance"] = "certainty", + score_threshold: Optional[float] = None, + ) -> _FindResult: + index_name = self._db_config.index_name + if search_field: + logging.warning( + 'Argument search_field is not supported for WeaviateDocumentIndex. Ignoring.' + ) + near_vector: Dict[str, Any] = { + "vector": query, + } + if score_threshold: + near_vector[score_name] = score_threshold + + results = ( + self._client.query.get(index_name, self.properties) + .with_near_vector( + near_vector, + ) + .with_limit(limit) + .with_additional([score_name, "vector"]) + .do() + ) + + docs, scores = self._format_response( + results["data"]["Get"][index_name], score_name + ) + return _FindResult(docs, parse_obj_as(NdArray, scores)) + + def _format_response( + self, results, score_name + ) -> Tuple[List[Dict[Any, Any]], List[Any]]: + """ + Format the response from Weaviate into a Tuple of DocList and scores + """ + + documents = [] + scores = [] + + for result in results: + score = result["_additional"][score_name] + scores.append(score) + + document = self._parse_weaviate_result(result) + documents.append(document) + + return documents, scores + + def find_batched( + self, + queries: Union[AnyTensor, DocList], + search_field: str = '', + limit: int = 10, + **kwargs, + ) -> FindResultBatched: + self._logger.debug('Executing `find_batched`') + if search_field != '': + raise ValueError( + 'Argument search_field is not supported for WeaviateDocumentIndex.\nSet search_field to an empty string to proceed.' + ) + embedding_field = self._get_embedding_field() + + if isinstance(queries, Sequence): + query_vec_list = self._get_values_by_column(queries, embedding_field) + query_vec_np = np.stack( + tuple(self._to_numpy(query_vec) for query_vec in query_vec_list) + ) + else: + query_vec_np = self._to_numpy(queries) + + da_list, scores = self._find_batched( + query_vec_np, search_field=search_field, limit=limit, **kwargs + ) + + if len(da_list) > 0 and isinstance(da_list[0], List): + da_list = [self._dict_list_to_docarray(docs) for docs in da_list] + + return FindResultBatched(documents=da_list, scores=scores) # type: ignore + + def _find_batched( + self, + queries: np.ndarray, + limit: int, + search_field: str = '', + score_name: Literal["certainty", "distance"] = "certainty", + score_threshold: Optional[float] = None, + ) -> _FindResultBatched: + qs = [] + for i, query in enumerate(queries): + near_vector: Dict[str, Any] = {"vector": query} + + if score_threshold: + near_vector[score_name] = score_threshold + + q = ( + self._client.query.get(self._db_config.index_name, self.properties) + .with_near_vector(near_vector) + .with_limit(limit) + .with_additional([score_name, "vector"]) + .with_alias(f'query_{i}') + ) + + qs.append(q) + + results = self._client.query.multi_get(qs).do() + + docs_and_scores = [ + self._format_response(result, score_name) + for result in results["data"]["Get"].values() + ] + + docs, scores = zip(*docs_and_scores) + return _FindResultBatched(list(docs), list(scores)) + + def _get_items(self, doc_ids: Sequence[str]) -> List[Dict]: + # TODO: warn when doc_ids > QUERY_MAXIMUM_RESULTS after + # https://github.com/weaviate/weaviate/issues/2792 + # is implemented + operands = [ + {"path": [DOCUMENTID], "operator": "Equal", "valueString": doc_id} + for doc_id in doc_ids + ] + where_filter = { + "operator": "Or", + "operands": operands, + } + + results = ( + self._client.query.get(self._db_config.index_name, self.properties) + .with_where(where_filter) + .with_additional("vector") + .do() + ) + + docs = [ + self._parse_weaviate_result(doc) + for doc in results["data"]["Get"][self._db_config.index_name] + ] + + return docs + + def _rewrite_documentid(self, document: Dict): + doc = document.copy() + + # rewrite the id to DOCUMENTID + document_id = doc.pop('id') + doc[DOCUMENTID] = document_id + + return doc + + def _parse_weaviate_result(self, result: Dict) -> Dict: + """ + Parse the result from weaviate to a format that is compatible with the schema + that was used to initialize weaviate with. + """ + + result = result.copy() + + # rewrite the DOCUMENTID to id + if DOCUMENTID in result: + result['id'] = result.pop(DOCUMENTID) + + # take the vector from the _additional field + if '_additional' in result and self.embedding_column: + additional_fields = result.pop('_additional') + if 'vector' in additional_fields: + result[self.embedding_column] = additional_fields['vector'] + + # convert any base64 encoded bytes column to bytes + self._decode_base64_properties_to_bytes(result) + + return result + + def _index(self, column_to_data: Dict[str, Generator[Any, None, None]]): + docs = self._transpose_col_value_dict(column_to_data) + index_name = self._db_config.index_name + + with self._client.batch as batch: + for doc in docs: + parsed_doc = self._rewrite_documentid(doc) + self._encode_bytes_columns_to_base64(parsed_doc) + self._convert_nonembedding_array_to_list(parsed_doc) + vector = ( + parsed_doc.pop(self.embedding_column) + if self.embedding_column + else None + ) + + batch.add_data_object( + uuid=weaviate.util.generate_uuid5(parsed_doc, index_name), + data_object=parsed_doc, + class_name=index_name, + vector=vector, + ) + + def _text_search( + self, query: str, limit: int, search_field: str = '' + ) -> _FindResult: + index_name = self._db_config.index_name + bm25 = {"query": query, "properties": [search_field]} + + results = ( + self._client.query.get(index_name, self.properties) + .with_bm25(bm25) + .with_limit(limit) + .with_additional(["score", "vector"]) + .do() + ) + + docs, scores = self._format_response( + results["data"]["Get"][index_name], "score" + ) + + return _FindResult(documents=docs, scores=parse_obj_as(NdArray, scores)) + + def _text_search_batched( + self, queries: Sequence[str], limit: int, search_field: str = '' + ) -> _FindResultBatched: + qs = [] + for i, query in enumerate(queries): + bm25 = {"query": query, "properties": [search_field]} + + q = ( + self._client.query.get(self._db_config.index_name, self.properties) + .with_bm25(bm25) + .with_limit(limit) + .with_additional(["score", "vector"]) + .with_alias(f'query_{i}') + ) + + qs.append(q) + + results = self._client.query.multi_get(qs).do() + + docs_and_scores = [ + self._format_response(result, "score") + for result in results["data"]["Get"].values() + ] + + docs, scores = zip(*docs_and_scores) + return _FindResultBatched(list(docs), list(scores)) + + def execute_query(self, query: Any, *args, **kwargs) -> Any: + da_class = DocList.__class_getitem__(cast(Type[BaseDoc], self._schema)) + + if isinstance(query, self.QueryBuilder): + batched_results = self._client.query.multi_get(query._queries).do() + batched_docs = batched_results["data"]["Get"].values() + + def f(doc): + # TODO: use + # return self._schema(**self._parse_weaviate_result(doc)) + # when https://github.com/weaviate/weaviate/issues/2858 + # is fixed + return self._schema.from_view(self._parse_weaviate_result(doc)) # type: ignore + + results = [ + da_class([f(doc) for doc in batched_doc]) + for batched_doc in batched_docs + ] + return results if len(results) > 1 else results[0] + + # TODO: validate graphql query string before sending it to weaviate + if isinstance(query, str): + return self._client.query.raw(query) + + def num_docs(self) -> int: + index_name = self._db_config.index_name + result = self._client.query.aggregate(index_name).with_meta_count().do() + # TODO: decorator to check for errors + total_docs = result["data"]["Aggregate"][index_name][0]["meta"]["count"] + + return total_docs + + def python_type_to_db_type(self, python_type: Type) -> Any: + """Map python type to database type.""" + for allowed_type in WEAVIATE_PY_VEC_TYPES: + if issubclass(python_type, allowed_type): + return 'number[]' + + py_weaviate_type_map = { + docarray.typing.ID: 'string', + str: 'text', + int: 'int', + float: 'number', + bool: 'boolean', + np.ndarray: 'number[]', + bytes: 'blob', + } + + for py_type, weaviate_type in py_weaviate_type_map.items(): + if issubclass(python_type, py_type): + return weaviate_type + + raise ValueError(f'Unsupported column type for {type(self)}: {python_type}') + + def build_query(self) -> BaseDocIndex.QueryBuilder: + return self.QueryBuilder(self) + + def _get_embedding_field(self): + for colname, colinfo in self._column_infos.items(): + # no need to check for missing is_embedding attribute because this check + # is done when the index is created + if colinfo.config.get('is_embedding', None): + return colname + + # just to pass mypy + return "" + + def _encode_bytes_columns_to_base64(self, doc): + for column in self.bytes_columns: + if doc[column] is not None: + doc[column] = base64.b64encode(doc[column]).decode("utf-8") + + def _decode_base64_properties_to_bytes(self, doc): + for column in self.bytes_columns: + if doc[column] is not None: + doc[column] = base64.b64decode(doc[column]) + + def _convert_nonembedding_array_to_list(self, doc): + for column in self.nonembedding_array_columns: + if doc[column] is not None: + doc[column] = doc[column].tolist() + + class QueryBuilder(BaseDocIndex.QueryBuilder): + def __init__(self, document_index): + self._queries = [ + document_index._client.query.get( + document_index._db_config.index_name, document_index.properties + ) + ] + + def build(self) -> Any: + num_queries = len(self._queries) + + for i in range(num_queries): + q = self._queries[i] + if self._is_hybrid_query(q): + self._make_proper_hybrid_query(q) + q.with_additional(["vector"]).with_alias(f'query_{i}') + + return self + + def _is_hybrid_query(self, query: weaviate.gql.get.GetBuilder) -> bool: + """ + Checks if a query has been composed with both a with_bm25 and a with_near_vector verb + """ + if not query._near_ask: + return False + else: + return query._bm25 and query._near_ask._content.get("vector", None) + + def _make_proper_hybrid_query( + self, query: weaviate.gql.get.GetBuilder + ) -> weaviate.gql.get.GetBuilder: + """ + Modifies a query to be a proper hybrid query. + + In weaviate, a query with with_bm25 and with_near_vector verb is not a hybrid query. + We need to use the with_hybrid verb to make it a hybrid query. + """ + + text_query = query._bm25.query + vector_query = query._near_ask._content["vector"] + hybrid_query = weaviate.gql.get.Hybrid( + query=text_query, vector=vector_query, alpha=0.5 + ) + + query._bm25 = None + query._near_ask = None + query._hybrid = hybrid_query + + def _overwrite_id(self, where_filter): + """ + Overwrite the id field in the where filter to DOCUMENTID + if the "id" field is present in the path + """ + for key, value in where_filter.items(): + if key == "path" and value == ["id"]: + where_filter[key] = [DOCUMENTID] + elif isinstance(value, dict): + self._overwrite_id(value) + elif isinstance(value, list): + for item in value: + if isinstance(item, dict): + self._overwrite_id(item) + + def find( + self, + query, + score_name: Literal["certainty", "distance"] = "certainty", + score_threshold: Optional[float] = None, + ) -> Any: + near_vector = { + "vector": query, + } + if score_threshold: + near_vector[score_name] = score_threshold + + self._queries[0] = self._queries[0].with_near_vector(near_vector) + return self + + def find_batched( + self, + queries, + score_name: Literal["certainty", "distance"] = "certainty", + score_threshold: Optional[float] = None, + ) -> Any: + adj_queries, adj_clauses = self._resize_queries_and_clauses( + self._queries, queries + ) + new_queries = [] + + for query, clause in zip(adj_queries, adj_clauses): + near_vector = { + "vector": clause, + } + if score_threshold: + near_vector[score_name] = score_threshold + + new_queries.append(query.with_near_vector(near_vector)) + + self._queries = new_queries + + return self + + def filter(self, where_filter) -> Any: + where_filter = where_filter.copy() + self._overwrite_id(where_filter) + self._queries[0] = self._queries[0].with_where(where_filter) + return self + + def filter_batched(self, filters) -> Any: + adj_queries, adj_clauses = self._resize_queries_and_clauses( + self._queries, filters + ) + new_queries = [] + + for query, clause in zip(adj_queries, adj_clauses): + clause = clause.copy() + self._overwrite_id(clause) + new_queries.append(query.with_where(clause)) + + self._queries = new_queries + + return self + + def text_search(self, query, search_field) -> Any: + bm25 = {"query": query, "properties": [search_field]} + self._queries[0] = self._queries[0].with_bm25(**bm25) + return self + + def text_search_batched(self, queries, search_field) -> Any: + adj_queries, adj_clauses = self._resize_queries_and_clauses( + self._queries, queries + ) + new_queries = [] + + for query, clause in zip(adj_queries, adj_clauses): + bm25 = {"query": clause, "properties": [search_field]} + new_queries.append(query.with_bm25(**bm25)) + + self._queries = new_queries + + return self + + def limit(self, limit: int) -> Any: + self._queries = [query.with_limit(limit) for query in self._queries] + return self + + def _resize_queries_and_clauses(self, queries, clauses): + """ + Adjust the length and content of queries and clauses so that we can compose + them element-wise + """ + num_clauses = len(clauses) + num_queries = len(queries) + + # if there's only one clause, then we assume that it should be applied + # to every query + if num_clauses == 1: + return queries, clauses * num_queries + # if there's only one query, then we can lengthen it to match the number + # of clauses + elif num_queries == 1: + return [copy.deepcopy(queries[0]) for _ in range(num_clauses)], clauses + # if the number of queries and clauses is the same, then we can just + # return them as-is + elif num_clauses == num_queries: + return queries, clauses + else: + raise ValueError( + f"Can't compose {num_clauses} clauses with {num_queries} queries" + )
diff --git a/tests/integrations/doc_index/weaviate/docker-compose.yml b/tests/integrations/doc_index/weaviate/docker-compose.yml new file mode 100644 --- /dev/null +++ b/tests/integrations/doc_index/weaviate/docker-compose.yml @@ -0,0 +1,27 @@ +version: '3.8' + +services: + + weaviate: + command: + - --host + - 0.0.0.0 + - --port + - '8080' + - --scheme + - http + image: semitechnologies/weaviate:1.18.3 + ports: + - "8080:8080" + restart: on-failure:0 + environment: + QUERY_DEFAULTS_LIMIT: 25 + AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'true' + PERSISTENCE_DATA_PATH: '/var/lib/weaviate' + DEFAULT_VECTORIZER_MODULE: 'none' + ENABLE_MODULES: '' + CLUSTER_HOSTNAME: 'node1' + LOG_LEVEL: debug # verbose + LOG_FORMAT: text + # LOG_LEVEL: trace # very verbose + GODEBUG: gctrace=1 # make go garbage collector verbose \ No newline at end of file diff --git a/tests/integrations/doc_index/weaviate/fixture_weaviate.py b/tests/integrations/doc_index/weaviate/fixture_weaviate.py new file mode 100644 --- /dev/null +++ b/tests/integrations/doc_index/weaviate/fixture_weaviate.py @@ -0,0 +1,41 @@ +import os +import time + +import pytest +import requests +import weaviate + +HOST = "http://localhost:8080" + + +cur_dir = os.path.dirname(os.path.abspath(__file__)) +weaviate_yml = os.path.abspath(os.path.join(cur_dir, 'docker-compose.yml')) + + [email protected](scope='session', autouse=True) +def start_storage(): + os.system(f"docker-compose -f {weaviate_yml} up -d --remove-orphans") + _wait_for_weaviate() + + yield + os.system(f"docker-compose -f {weaviate_yml} down --remove-orphans") + + +def _wait_for_weaviate(): + while True: + try: + response = requests.get(f"{HOST}/v1/.well-known/ready") + if response.status_code == 200: + return + else: + time.sleep(0.5) + except requests.exceptions.ConnectionError: + time.sleep(1) + + [email protected] +def weaviate_client(start_storage): + client = weaviate.Client(HOST) + client.schema.delete_all() + yield client + client.schema.delete_all() diff --git a/tests/integrations/doc_index/weaviate/test_column_config_weaviate.py b/tests/integrations/doc_index/weaviate/test_column_config_weaviate.py new file mode 100644 --- /dev/null +++ b/tests/integrations/doc_index/weaviate/test_column_config_weaviate.py @@ -0,0 +1,33 @@ +# TODO: enable ruff qa on this file when we figure out why it thinks weaviate_client is +# redefined at each test that fixture +# ruff: noqa +from pydantic import Field + +from docarray import BaseDoc +from docarray.index.backends.weaviate import WeaviateDocumentIndex +from tests.integrations.doc_index.weaviate.fixture_weaviate import ( # noqa: F401 + start_storage, + weaviate_client, +) + + +def test_column_config(weaviate_client): + def get_text_field_data_type(store, index_name): + props = store._client.schema.get(index_name)["properties"] + text_field = [p for p in props if p["name"] == "text"][0] + + return text_field["dataType"][0] + + class TextDoc(BaseDoc): + text: str = Field() + + class StringDoc(BaseDoc): + text: str = Field(col_type="string") + + dbconfig = WeaviateDocumentIndex.DBConfig(index_name="TextDoc") + store = WeaviateDocumentIndex[TextDoc](db_config=dbconfig) + assert get_text_field_data_type(store, "TextDoc") == "text" + + dbconfig = WeaviateDocumentIndex.DBConfig(index_name="StringDoc") + store = WeaviateDocumentIndex[StringDoc](db_config=dbconfig) + assert get_text_field_data_type(store, "StringDoc") == "string" diff --git a/tests/integrations/doc_index/weaviate/test_find_weaviate.py b/tests/integrations/doc_index/weaviate/test_find_weaviate.py new file mode 100644 --- /dev/null +++ b/tests/integrations/doc_index/weaviate/test_find_weaviate.py @@ -0,0 +1,66 @@ +# TODO: enable ruff qa on this file when we figure out why it thinks weaviate_client is +# redefined at each test that fixture +# ruff: noqa +import numpy as np +import pytest +import torch +from pydantic import Field + +from docarray import BaseDoc +from docarray.index.backends.weaviate import WeaviateDocumentIndex +from docarray.typing import TorchTensor +from tests.integrations.doc_index.weaviate.fixture_weaviate import ( # noqa: F401 + start_storage, + weaviate_client, +) + + +def test_find_torch(weaviate_client): + class TorchDoc(BaseDoc): + tens: TorchTensor[10] = Field(dims=10, is_embedding=True) + + store = WeaviateDocumentIndex[TorchDoc]() + + index_docs = [ + TorchDoc(tens=np.random.rand(10).astype(dtype=np.float32)) for _ in range(10) + ] + store.index(index_docs) + + query = index_docs[-1] + docs, scores = store.find(query, limit=5) + + assert len(docs) == 5 + assert len(scores) == 5 + for doc in docs: + assert isinstance(doc.tens, TorchTensor) + + assert docs[0].id == index_docs[-1].id + assert torch.allclose(docs[0].tens, index_docs[-1].tens) + + [email protected] +def test_find_tensorflow(): + from docarray.typing import TensorFlowTensor + + class TfDoc(BaseDoc): + tens: TensorFlowTensor[10] = Field(dims=10, is_embedding=True) + + store = WeaviateDocumentIndex[TfDoc]() + + index_docs = [ + TfDoc(tens=np.random.rand(10).astype(dtype=np.float32)) for _ in range(10) + ] + store.index(index_docs) + + query = index_docs[-1] + docs, scores = store.find(query, limit=5) + + assert len(docs) == 5 + assert len(scores) == 5 + for doc in docs: + assert isinstance(doc.tens, TensorFlowTensor) + + assert docs[0].id == index_docs[-1].id + assert np.allclose( + docs[0].tens.unwrap().numpy(), index_docs[-1].tens.unwrap().numpy() + ) diff --git a/tests/integrations/doc_index/weaviate/test_index_get_del_weaviate.py b/tests/integrations/doc_index/weaviate/test_index_get_del_weaviate.py new file mode 100644 --- /dev/null +++ b/tests/integrations/doc_index/weaviate/test_index_get_del_weaviate.py @@ -0,0 +1,452 @@ +# TODO: enable ruff qa on this file when we figure out why it thinks weaviate_client is +# redefined at each test that fixture +# ruff: noqa +import logging + +import numpy as np +import pytest +from pydantic import Field + +from docarray import BaseDoc +from docarray.documents import ImageDoc, TextDoc +from docarray.index.backends.weaviate import ( + DOCUMENTID, + EmbeddedOptions, + WeaviateDocumentIndex, +) +from docarray.typing import NdArray +from tests.integrations.doc_index.weaviate.fixture_weaviate import ( # noqa: F401 + HOST, + start_storage, + weaviate_client, +) + + +class SimpleDoc(BaseDoc): + tens: NdArray[10] = Field(dim=1000, is_embedding=True) + + +class Document(BaseDoc): + embedding: NdArray[2] = Field(dim=2, is_embedding=True) + text: str = Field() + + +class NestedDocument(BaseDoc): + text: str = Field() + child: Document + + [email protected] +def ten_simple_docs(): + return [SimpleDoc(tens=np.random.randn(10)) for _ in range(10)] + + [email protected] +def documents(): + texts = ["lorem ipsum", "dolor sit amet", "consectetur adipiscing elit"] + embeddings = [[10, 10], [10.5, 10.5], [-100, -100]] + + # create the docs by enumerating from 1 and use that as the id + docs = [ + Document(id=str(i), embedding=embedding, text=text) + for i, (embedding, text) in enumerate(zip(embeddings, texts)) + ] + + yield docs + + [email protected] +def test_store(weaviate_client, documents): + store = WeaviateDocumentIndex[Document]() + store.index(documents) + yield store + + +def test_index_simple_schema(weaviate_client, ten_simple_docs): + store = WeaviateDocumentIndex[SimpleDoc]() + store.index(ten_simple_docs) + assert store.num_docs() == 10 + + for doc in ten_simple_docs: + doc_id = doc.id + doc_embedding = doc.tens + + result = ( + weaviate_client.query.get("Document", DOCUMENTID) + .with_additional("vector") + .with_where( + {"path": [DOCUMENTID], "operator": "Equal", "valueString": doc_id} + ) + .do() + ) + + result = result["data"]["Get"]["Document"][0] + assert result[DOCUMENTID] == doc_id + assert np.allclose(result["_additional"]["vector"], doc_embedding) + + +def test_validate_columns(weaviate_client): + dbconfig = WeaviateDocumentIndex.DBConfig(host=HOST) + + class InvalidDoc1(BaseDoc): + tens: NdArray[10] = Field(dim=1000, is_embedding=True) + tens2: NdArray[10] = Field(dim=1000, is_embedding=True) + + class InvalidDoc2(BaseDoc): + tens: int = Field(dim=1000, is_embedding=True) + + with pytest.raises(ValueError, match=r"Only one column can be marked as embedding"): + WeaviateDocumentIndex[InvalidDoc1](db_config=dbconfig) + + with pytest.raises(ValueError, match=r"marked as embedding but is not of type"): + WeaviateDocumentIndex[InvalidDoc2](db_config=dbconfig) + + +def test_find(weaviate_client, caplog): + class Document(BaseDoc): + embedding: NdArray[2] = Field(dim=2, is_embedding=True) + + vectors = [[10, 10], [10.5, 10.5], [-100, -100]] + docs = [Document(embedding=vector) for vector in vectors] + + store = WeaviateDocumentIndex[Document]() + store.index(docs) + + query = [10.1, 10.1] + + results = store.find( + query, search_field='', limit=3, score_name="distance", score_threshold=1e-2 + ) + assert len(results) == 2 + + results = store.find(query, search_field='', limit=3, score_threshold=0.99) + assert len(results) == 2 + + with pytest.raises( + ValueError, + match=r"Argument search_field is not supported for WeaviateDocumentIndex", + ): + store.find(query, search_field="foo", limit=10) + + +def test_find_batched(weaviate_client, caplog): + class Document(BaseDoc): + embedding: NdArray[2] = Field(dim=2, is_embedding=True) + + vectors = [[10, 10], [10.5, 10.5], [-100, -100]] + docs = [Document(embedding=vector) for vector in vectors] + + store = WeaviateDocumentIndex[Document]() + store.index(docs) + + queries = np.array([[10.1, 10.1], [-100, -100]]) + + results = store.find_batched( + queries, search_field='', limit=3, score_name="distance", score_threshold=1e-2 + ) + assert len(results) == 2 + assert len(results.documents[0]) == 2 + assert len(results.documents[1]) == 1 + + results = store.find_batched( + queries, search_field='', limit=3, score_name="certainty" + ) + assert len(results) == 2 + assert len(results.documents[0]) == 3 + assert len(results.documents[1]) == 3 + + with pytest.raises( + ValueError, + match=r"Argument search_field is not supported for WeaviateDocumentIndex", + ): + store.find_batched(queries, search_field="foo", limit=10) + + [email protected]( + "filter_query, expected_num_docs", + [ + ({"path": ["text"], "operator": "Equal", "valueText": "lorem ipsum"}, 1), + ({"path": ["text"], "operator": "Equal", "valueText": "foo"}, 0), + ({"path": ["id"], "operator": "Equal", "valueString": "1"}, 1), + ], +) +def test_filter(test_store, filter_query, expected_num_docs): + docs = test_store.filter(filter_query, limit=3) + actual_num_docs = len(docs) + + assert actual_num_docs == expected_num_docs + + [email protected]( + "filter_queries, expected_num_docs", + [ + ( + [ + {"path": ["text"], "operator": "Equal", "valueText": "lorem ipsum"}, + {"path": ["text"], "operator": "Equal", "valueText": "foo"}, + ], + [1, 0], + ), + ( + [ + {"path": ["id"], "operator": "Equal", "valueString": "1"}, + {"path": ["id"], "operator": "Equal", "valueString": "2"}, + ], + [1, 0], + ), + ], +) +def test_filter_batched(test_store, filter_queries, expected_num_docs): + filter_queries = [ + {"path": ["text"], "operator": "Equal", "valueText": "lorem ipsum"}, + {"path": ["text"], "operator": "Equal", "valueText": "foo"}, + ] + + results = test_store.filter_batched(filter_queries, limit=3) + actual_num_docs = [len(docs) for docs in results] + assert actual_num_docs == expected_num_docs + + +def test_text_search(test_store): + results = test_store.text_search(query="lorem", search_field="text", limit=3) + assert len(results.documents) == 1 + + +def test_text_search_batched(test_store): + text_queries = ["lorem", "foo"] + + results = test_store.text_search_batched( + queries=text_queries, search_field="text", limit=3 + ) + assert len(results.documents[0]) == 1 + assert len(results.documents[1]) == 0 + + +def test_del_items(test_store): + del test_store[["1", "2"]] + assert test_store.num_docs() == 1 + + +def test_get_items(test_store): + docs = test_store[["1", "2"]] + assert len(docs) == 2 + assert set(doc.id for doc in docs) == {'1', '2'} + + +def test_index_nested_documents(weaviate_client): + store = WeaviateDocumentIndex[NestedDocument]() + document = NestedDocument( + text="lorem ipsum", child=Document(embedding=[10, 10], text="dolor sit amet") + ) + store.index([document]) + assert store.num_docs() == 1 + + [email protected]( + "search_field, query, expected_num_docs", + [ + ("text", "lorem", 1), + ("child__text", "dolor", 1), + ("text", "foo", 0), + ("child__text", "bar", 0), + ], +) +def test_text_search_nested_documents( + weaviate_client, search_field, query, expected_num_docs +): + store = WeaviateDocumentIndex[NestedDocument]() + document = NestedDocument( + text="lorem ipsum", child=Document(embedding=[10, 10], text="dolor sit amet") + ) + store.index([document]) + + results = store.text_search(query=query, search_field=search_field, limit=3) + + assert len(results.documents) == expected_num_docs + + +def test_reuse_existing_schema(weaviate_client, caplog): + WeaviateDocumentIndex[SimpleDoc]() + + with caplog.at_level(logging.DEBUG): + WeaviateDocumentIndex[SimpleDoc]() + assert "Will reuse existing schema" in caplog.text + + +def test_query_builder(test_store): + query_embedding = [10.25, 10.25] + query_text = "ipsum" + where_filter = {"path": ["id"], "operator": "Equal", "valueString": "1"} + q = ( + test_store.build_query() + .find(query=query_embedding) + .filter(where_filter) + .build() + ) + + docs = test_store.execute_query(q) + assert len(docs) == 1 + + q = ( + test_store.build_query() + .text_search(query=query_text, search_field="text") + .build() + ) + + docs = test_store.execute_query(q) + assert len(docs) == 1 + + +def test_batched_query_builder(test_store): + query_embeddings = [[10.25, 10.25], [-100, -100]] + query_texts = ["ipsum", "foo"] + where_filters = [{"path": ["id"], "operator": "Equal", "valueString": "1"}] + + q = ( + test_store.build_query() + .find_batched( + queries=query_embeddings, score_name="certainty", score_threshold=0.99 + ) + .filter_batched(filters=where_filters) + .build() + ) + + docs = test_store.execute_query(q) + assert len(docs[0]) == 1 + assert len(docs[1]) == 0 + + q = ( + test_store.build_query() + .text_search_batched(queries=query_texts, search_field="text") + .build() + ) + + docs = test_store.execute_query(q) + assert len(docs[0]) == 1 + assert len(docs[1]) == 0 + + +def test_raw_graphql(test_store): + graphql_query = """ + { + Aggregate { + Document { + meta { + count + } + } + } + } + """ + + results = test_store.execute_query(graphql_query) + num_docs = results["data"]["Aggregate"]["Document"][0]["meta"]["count"] + + assert num_docs == 3 + + +def test_hybrid_query(test_store): + query_embedding = [10.25, 10.25] + query_text = "ipsum" + where_filter = {"path": ["id"], "operator": "Equal", "valueString": "1"} + + q = ( + test_store.build_query() + .find(query=query_embedding) + .text_search(query=query_text, search_field="text") + .filter(where_filter) + .build() + ) + + docs = test_store.execute_query(q) + assert len(docs) == 1 + + +def test_hybrid_query_batched(test_store): + query_embeddings = [[10.25, 10.25], [-100, -100]] + query_texts = ["dolor", "elit"] + + q = ( + test_store.build_query() + .find_batched( + queries=query_embeddings, score_name="certainty", score_threshold=0.99 + ) + .text_search_batched(queries=query_texts, search_field="text") + .build() + ) + + docs = test_store.execute_query(q) + assert docs[0][0].id == '1' + assert docs[1][0].id == '2' + + +def test_index_multi_modal_doc(): + class MyMultiModalDoc(BaseDoc): + image: ImageDoc + text: TextDoc + + store = WeaviateDocumentIndex[MyMultiModalDoc]() + + doc = [ + MyMultiModalDoc( + image=ImageDoc(embedding=np.random.randn(128)), text=TextDoc(text='hello') + ) + ] + store.index(doc) + + id_ = doc[0].id + assert store[id_].id == id_ + assert np.all(store[id_].image.embedding == doc[0].image.embedding) + assert store[id_].text.text == doc[0].text.text + + +def test_index_document_with_bytes(weaviate_client): + doc = ImageDoc(id="1", url="www.foo.com", bytes_=b"foo") + + store = WeaviateDocumentIndex[ImageDoc]() + store.index([doc]) + + results = store.filter( + filter_query={"path": ["id"], "operator": "Equal", "valueString": "1"} + ) + + assert doc == results[0] + + +def test_index_document_with_no_embeddings(weaviate_client): + # define a document that does not have any field where is_embedding=True + class Document(BaseDoc): + not_embedding: NdArray[2] = Field(dim=2) + text: str + + doc = Document(not_embedding=[2, 5], text="dolor sit amet", id="1") + + store = WeaviateDocumentIndex[Document]() + + store.index([doc]) + + results = store.filter( + filter_query={"path": ["id"], "operator": "Equal", "valueString": "1"} + ) + + assert doc == results[0] + + +def test_limit_query_builder(test_store): + query_vector = [10.25, 10.25] + q = test_store.build_query().find(query=query_vector).limit(2) + + docs = test_store.execute_query(q) + assert len(docs) == 2 + + [email protected] +def test_embedded_weaviate(): + class Document(BaseDoc): + text: str + + embedded_options = EmbeddedOptions() + db_config = WeaviateDocumentIndex.DBConfig(embedded_options=embedded_options) + store = WeaviateDocumentIndex[Document](db_config=db_config) + + assert store._client._connection.embedded_db
DocumentIndex: support for Weaviate Implement a Document Index backed by Weaviate. **References:** - Implementation manual: https://github.com/docarray/docarray/blob/feat-rewrite-v2/docs/tutorials/add_doc_index.md - Document Index design doc (slightly outdated, but the main ideas remain): https://lightning-scent-57a.notion.site/Document-Stores-v2-design-doc-f11d6fe6ecee43f49ef88e0f1bf80b7f - Original PR adding Document Index base class: https://github.com/docarray/docarray/pull/1124
@JohannesMessner Can I do this? > @JohannesMessner Can I do this? Perfect, assigned!
2023-04-12T13:45:51
docarray/docarray
1,454
docarray__docarray-1454
[ "1452" ]
a76cc6159ab1aaf6932b46e639a6c2396ef751f5
diff --git a/docarray/index/abstract.py b/docarray/index/abstract.py --- a/docarray/index/abstract.py +++ b/docarray/index/abstract.py @@ -900,3 +900,6 @@ def _dict_list_to_docarray(self, dict_list: Sequence[Dict[str, Any]]) -> DocList doc_list = [self._convert_dict_to_doc(doc_dict, self._schema) for doc_dict in dict_list] # type: ignore docs_cls = DocList.__class_getitem__(cast(Type[BaseDoc], self._schema)) return docs_cls(doc_list) + + def __len__(self) -> int: + return self.num_docs()
diff --git a/tests/index/base_classes/test_base_doc_store.py b/tests/index/base_classes/test_base_doc_store.py --- a/tests/index/base_classes/test_base_doc_store.py +++ b/tests/index/base_classes/test_base_doc_store.py @@ -71,7 +71,7 @@ def python_type_to_db_type(self, x): return str _index = _identity - num_docs = _identity + num_docs = lambda n: 3 _del_items = _identity _get_items = _identity execute_query = _identity @@ -572,3 +572,9 @@ def test_validate_search_fields(): # 'ten' is not a valid field with pytest.raises(ValueError): index._validate_search_field('ten') + + +def test_len(): + store = DummyDocIndex[SimpleDoc]() + count = len(store) + assert count == 3
add len on DocIndex # Context len(db) should return db.num_docs when db is a DocIndex
2023-04-25T15:43:15
docarray/docarray
1,459
docarray__docarray-1459
[ "1442" ]
8df9e7f3ae700ee84f766d38fd4cc2fb63908567
diff --git a/docarray/array/doc_list/io.py b/docarray/array/doc_list/io.py --- a/docarray/array/doc_list/io.py +++ b/docarray/array/doc_list/io.py @@ -46,8 +46,8 @@ T = TypeVar('T', bound='IOMixinArray') T_doc = TypeVar('T_doc', bound=BaseDoc) -ARRAY_PROTOCOLS = {'protobuf-array', 'pickle-array'} -SINGLE_PROTOCOLS = {'pickle', 'protobuf'} +ARRAY_PROTOCOLS = {'protobuf-array', 'pickle-array', 'json-array'} +SINGLE_PROTOCOLS = {'pickle', 'protobuf', 'json'} ALLOWED_PROTOCOLS = ARRAY_PROTOCOLS.union(SINGLE_PROTOCOLS) ALLOWED_COMPRESSIONS = {'lz4', 'bz2', 'lzma', 'zlib', 'gzip'} @@ -180,6 +180,8 @@ def _write_bytes( f.write(self.to_protobuf().SerializePartialToString()) elif protocol == 'pickle-array': f.write(pickle.dumps(self)) + elif protocol == 'json-array': + f.write(self.to_json()) elif protocol in SINGLE_PROTOCOLS: f.write( b''.join( @@ -575,7 +577,11 @@ def _load_binary_all( else: d = fp.read() - if protocol is not None and protocol in ('pickle-array', 'protobuf-array'): + if protocol is not None and protocol in ( + 'pickle-array', + 'protobuf-array', + 'json-array', + ): if _get_compress_ctx(algorithm=compress) is not None: d = _decompress_bytes(d, algorithm=compress) compress = None @@ -590,6 +596,9 @@ def _load_binary_all( elif protocol is not None and protocol == 'pickle-array': return pickle.loads(d) + elif protocol is not None and protocol == 'json-array': + return cls.from_json(d) + # Binary format for streaming case else: from rich import filesize
diff --git a/tests/units/array/test_array_save_load.py b/tests/units/array/test_array_save_load.py --- a/tests/units/array/test_array_save_load.py +++ b/tests/units/array/test_array_save_load.py @@ -16,7 +16,7 @@ class MyDoc(BaseDoc): @pytest.mark.slow @pytest.mark.parametrize( - 'protocol', ['pickle-array', 'protobuf-array', 'protobuf', 'pickle'] + 'protocol', ['pickle-array', 'protobuf-array', 'protobuf', 'pickle', 'json-array'] ) @pytest.mark.parametrize('compress', ['lz4', 'bz2', 'lzma', 'zlib', 'gzip', None]) @pytest.mark.parametrize('show_progress', [False, True]) @@ -52,7 +52,7 @@ def test_array_save_load_binary(protocol, compress, tmp_path, show_progress): @pytest.mark.slow @pytest.mark.parametrize( - 'protocol', ['pickle-array', 'protobuf-array', 'protobuf', 'pickle'] + 'protocol', ['pickle-array', 'protobuf-array', 'protobuf', 'pickle', 'json-array'] ) @pytest.mark.parametrize('compress', ['lz4', 'bz2', 'lzma', 'zlib', 'gzip', None]) @pytest.mark.parametrize('show_progress', [False, True])
add json-array to save binaries # Context DocList.save_binary does not support json protocol. It should IMO
2023-04-26T14:05:06
docarray/docarray
1,641
docarray__docarray-1641
[ "1638" ]
7f91e21737eacad0d4c7aaaec2445f5eaab3a7f7
diff --git a/docarray/array/doc_vec/column_storage.py b/docarray/array/doc_vec/column_storage.py --- a/docarray/array/doc_vec/column_storage.py +++ b/docarray/array/doc_vec/column_storage.py @@ -91,6 +91,21 @@ def __getitem__(self: T, item: IndexIterType) -> T: self.tensor_type, ) + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ColumnStorage): + return False + if self.tensor_type != other.tensor_type: + return False + for col_map_self, col_map_other in zip(self.columns.maps, other.columns.maps): + if col_map_self.keys() != col_map_other.keys(): + return False + for key_self in col_map_self.keys(): + if key_self == 'id': + continue + if col_map_self[key_self] != col_map_other[key_self]: + return False + return True + class ColumnStorageView(dict, MutableMapping[str, Any]): index: int diff --git a/docarray/array/doc_vec/doc_vec.py b/docarray/array/doc_vec/doc_vec.py --- a/docarray/array/doc_vec/doc_vec.py +++ b/docarray/array/doc_vec/doc_vec.py @@ -584,6 +584,17 @@ def __iter__(self): def __len__(self): return len(self._storage) + def __eq__(self, other: Any) -> bool: + if not isinstance(other, DocVec): + return False + if self.doc_type != other.doc_type: + return False + if self.tensor_type != other.tensor_type: + return False + if self._storage != other._storage: + return False + return True + #################### # IO related # ####################
diff --git a/tests/units/array/stack/test_array_stacked.py b/tests/units/array/stack/test_array_stacked.py --- a/tests/units/array/stack/test_array_stacked.py +++ b/tests/units/array/stack/test_array_stacked.py @@ -585,3 +585,35 @@ def test_doc_view_dict(batch): d = doc_view_two.dict() assert d['tensor'].shape == (3, 224, 224) assert d['id'] == doc_view_two.id + + +def test_doc_vec_equality(): + class Text(BaseDoc): + text: str + + da = DocVec[Text]([Text(text='hello') for _ in range(10)]) + da2 = DocList[Text]([Text(text='hello') for _ in range(10)]) + + assert da != da2 + assert da == da2.to_doc_vec() + + +def test_doc_vec_nested(batch_nested_doc): + batch, Doc, Inner = batch_nested_doc + batch2 = DocVec[Doc]([Doc(inner=Inner(hello='hello')) for _ in range(10)]) + + assert batch == batch2 + + +def test_doc_vec_tensor_type(): + class ImageDoc(BaseDoc): + tensor: AnyTensor + + da = DocVec[ImageDoc]([ImageDoc(tensor=np.zeros((3, 224, 224))) for _ in range(10)]) + + da2 = DocVec[ImageDoc]( + [ImageDoc(tensor=torch.zeros(3, 224, 224)) for _ in range(10)], + tensor_type=TorchTensor, + ) + + assert da != da2
Bug: Equality of DocVec Equality between instances of DocVec does not seem to work properly: ```python from docarray import BaseDoc, DocList class CustomDocument(BaseDoc): image: str da = DocList[CustomDocument]( [CustomDocument(image='hi') for _ in range(10)] ).to_doc_vec() da2 = DocList[CustomDocument]( [CustomDocument(image='hi') for _ in range(10)] ).to_doc_vec() print(da == da2) ``` ```bash False ```
I can take this @JohannesMessner. Should this follow the same implementation as `DocList.__eq__()`? > I can take this @JohannesMessner. Should this follow the same implementation as `DocList.__eq__()`? Honestly I haven't checked that, but it is probably a good place to get inspiration from
2023-06-12T12:00:29
docarray/docarray
1,643
docarray__docarray-1643
[ "1560" ]
8f25887d13f27338a99199ebd85462a4d6764615
diff --git a/docarray/base_doc/doc.py b/docarray/base_doc/doc.py --- a/docarray/base_doc/doc.py +++ b/docarray/base_doc/doc.py @@ -311,7 +311,11 @@ def dict( ) -> 'DictStrAny': """ Generate a dictionary representation of the model, optionally specifying - which fields to include or exclude. + which fields to include or exclude. The method also includes the attributes + and their values when attributes are objects of class types which can include + nesting. This method differs from the `dict()` method of python which only + prints the methods and attributes of the object and only the type of the + attribute when attributes are types of other class. """
docs: add docs for the dict() method # Context we need to document the behavior of calling `dict()` on a BaseDoc. Especially with nested DocList. ```python class InnerDoc(BaseDoc): x: int class MyDoc(BaseDoc): l: DocList[InnerDoc] doc = MyDoc(l=[InnerDoc(x=1), InnerDoc(x=2)]) print(f'{doc.dict()=}') #> doc_view.dict()={'id': 'ab65fc52a60d1da1ce6196c100943e1f', 'l': [{'id': 'e218c3a6904cbbd0f48ccd10130c9f78', 'x': 1}, {'id': 'e30bf3d613bf5c3e805faf0c0dc0f704', 'x': 2}]} ``` and we need to explain how using `dict(doc)` is different from using `doc.dict()`
Hi, can I take this issue up? I would like to contribute Hey @shivance , For sure, I will assign it to you. Hi. I can take it up if a fix for this has not already been merged. I went through the library and looked at the `BaseDoc` class and had a couple of questions 1. Would I be documenting the behaviour of [this](https://github.com/docarray/docarray/blob/29c2d23a618704e9ed13108c754e09c6ef053a93/docarray/base_doc/doc.py#L301) class method inside `BaseDoc` 2. From what I can understand, if `dict(doc)` is called on a `BaseDoc` object it should return the attributes set and calling `doc.dict()` would return model created as shown in the issue description. 3. Can you guide me on what the appropriate documentation would be? @punndcoder28 You could take this up ! Sorry, I've got a bit busy lately, it would be delayed at my end. @punndcoder28 I suggest you start by writing the a small documentation example in this issue. Something with code snippets to explain the behavior. Then I will point you where you should add it in the documentation Sure @samsja will do that. I want to know if I have understood the working of both the methods as mentioned earlier in [this](https://github.com/docarray/docarray/issues/1560#issuecomment-1574760721) comment. If that is confirmed will work on writing a draft changes here along with the code changes for your reviews. > if dict(doc) is called on a BaseDoc object it should return the attributes set I am not sure what you mean in this sentence Sorry, should have worded it better. The below example should help. Suppose I have a class `MyClass` like below ``` class MyClass: def __init__(self, name, age): self.name = name self.age = age ``` and when I initialise the object `class_ob = MyClass('name', 20)` and print `print(dict(class_obj))` it will print ``` {'name': 'name', 'age': 20} ``` Would that be the same for when `dict(doc)` is called from the issue description I suggest you to run the example in description and look at the difference between calling: * print(f'{doc.dict()=}') * print(f'{dict(doc)}') In your example it will be the same, there will be a real difference only if there is a nested doc Ok. Will run the code and check the difference out. But shouldn't it not print the attributes of the inherited classes as well? yes it should Ran the code from the issue description and got the below output ``` doc.dict()={'id': '31a728bdc668421ecad26148484d4812', 'l': [{'id': 'ce15f8dfd26b4d1bfb7599e07c81d358', 'x': 1}, {'id': '2da3af3f506536d3d4b939e147ab3b61', 'x': 2}]} dict(doc)={'id': '31a728bdc668421ecad26148484d4812', 'l': <DocList[InnerDoc] (length=2)>} ``` The stark difference I see between the two `dict` methods is `doc.dict()` would print the attribute details even when there is nesting but `dict(doc)` prints the attributes on the same level as the object but when there is nesting it will only print the type of the attribute which has the nesting, like how it has done for `'l': <DocList[InnerDoc] (length=2)>`. Have I understood it correctly? Please review the initial draft of the doc changes I want to propose 1. `dict(doc)`: The `dict()` method when called with the argument of type `BaseDoc` returns the class attribute values set. Let us consider the below example ``` class MyDoc(BaseDoc): my_attribute: str doc_object = MyDoc(my_attribute='my_attribute_value') print(f'{dict(doc_object)=}') ``` The above code example prints the following ``` {'id': '7072482715ad496140b488120c4e2f98', 'my_attribute': 'my_attribute_value'} ``` It is also worth noting that when there are attributes with types such as `List`, `Dict`, `Tuple`, `DocList` or other types which can have nested objects, then the output of this method will only specify the type of the object. Consider the below example ``` from docarray import BaseDoc, DocList class ParentDoc(BaseDoc): parent_attribute: str class MyDoc(BaseDoc): my_attribute: DocList[ParentDoc] doc_object = MyDoc(my_attribute=[ParentDoc(parent_attribute='first'), ParentDoc(parent_attribute='second')]) print(f'{dict(doc_object)=}') ``` which will output ``` {'id': '5e0cad5cf70c14873ead84c54f610358', 'my_attribute': <DocList[ParentDoc] (length=2)>} ``` 2. `doc.dict()`: The `dict()` method when called on an object of type `BaseDoc` or it's inherited classes will print out the fields and the contained values even when there is nesting. Let us consider the below example ``` from docarray import BaseDoc, DocList class ParentDoc(BaseDoc): parent_attribute: str class MyDoc(BaseDoc): my_attribute: DocList[ParentDoc] doc_object = MyDoc(my_attribute=[ParentDoc(parent_attribute='first'), ParentDoc(parent_attribute='second')]) print(f'{doc_object.dict()=}') ``` The output of the `print(f'{doc_object.dict()=}')` will print the values contained within the `my_attribute` class attribute ``` {'id': 'fc902ad3d53f270c1a0d6c7be3220141', 'my_attribute': [{'id': '02d4156a11b6f345cb7185b2a88ebb0c', 'parent_attribute': 'first'}, {'id': '8bf3dc388965a72d2bd102c6dc1201ec', 'parent_attribute': 'second'}]} ``` @samsja Would be awesome if you can take a look at the initial draft and suggest changes. Thanks! hey @punndcoder28 this looks nice, could you open a PR so that I can suggest you edit directly there ? Thanks for you contribution :rocket:
2023-06-12T17:15:39
docarray/docarray
1,651
docarray__docarray-1651
[ "1357" ]
62ad22aa8ae3617b9464b904cd33b3115d011781
diff --git a/docarray/index/backends/weaviate.py b/docarray/index/backends/weaviate.py --- a/docarray/index/backends/weaviate.py +++ b/docarray/index/backends/weaviate.py @@ -225,9 +225,7 @@ def _create_schema(self) -> None: schema["properties"] = properties schema["class"] = self.index_name - # TODO: Use exists() instead of contains() when available - # see https://github.com/weaviate/weaviate-python-client/issues/232 - if self._client.schema.contains(schema): + if self._client.schema.exists(self.index_name): logging.warning( f"Found index {self.index_name} with schema {schema}. Will reuse existing schema." )
Weaviate: Add more robust method to detect existing index **Is your feature request related to a problem? Please describe.** An index should be considered as exist when there is a schema with the exist name and properties. **Describe the solution you'd like** Use the client's `exists` instead of `contains` method to detect an existing index name. **Describe alternatives you've considered** NA **Additional context** Wait for weaviate/weaviate-python-client#232 to be implemented
FYI, support has been added. we can do `client.schema.exists(INDEX_NAME)`
2023-06-15T07:25:28
docarray/docarray
1,654
docarray__docarray-1654
[ "1653" ]
7f91e21737eacad0d4c7aaaec2445f5eaab3a7f7
diff --git a/docarray/index/backends/weaviate.py b/docarray/index/backends/weaviate.py --- a/docarray/index/backends/weaviate.py +++ b/docarray/index/backends/weaviate.py @@ -599,7 +599,7 @@ def _text_search( results = ( self._client.query.get(index_name, self.properties) - .with_bm25(bm25) + .with_bm25(**bm25) .with_limit(limit) .with_additional(["score", "vector"]) .do() @@ -620,7 +620,7 @@ def _text_search_batched( q = ( self._client.query.get(self.index_name, self.properties) - .with_bm25(bm25) + .with_bm25(**bm25) .with_limit(limit) .with_additional(["score", "vector"]) .with_alias(f'query_{i}')
Weaviate: update text search to match latest client's requirements Starting from 3.15.6, with_bm25 no longer expects a dictionary. See weaviate/weaviate-python-client#290 for details. <!-- Edit the body of your new issue then click the ✓ "Create Issue" button in the top right of the editor. The first line will be the issue title. Assignees and Labels follow after a blank line. Leave an empty line before beginning the body of the issue. -->
2023-06-15T10:17:49
docarray/docarray
1,769
docarray__docarray-1769
[ "1766" ]
cc2339db44626e622f3b2f354d0c5f8d8a0b20ea
diff --git a/docarray/array/doc_list/io.py b/docarray/array/doc_list/io.py --- a/docarray/array/doc_list/io.py +++ b/docarray/array/doc_list/io.py @@ -183,7 +183,7 @@ def _write_bytes( elif protocol == 'pickle-array': f.write(pickle.dumps(self)) elif protocol == 'json-array': - f.write(self.to_json()) + f.write(self.to_json().encode()) elif protocol in SINGLE_PROTOCOLS: f.write( b''.join( @@ -327,11 +327,11 @@ def from_json( json_docs = orjson.loads(file) return cls([cls.doc_type(**v) for v in json_docs]) - def to_json(self) -> bytes: + def to_json(self) -> str: """Convert the object into JSON bytes. Can be loaded via `.from_json`. :return: JSON serialization of `DocList` """ - return orjson_dumps(self) + return orjson_dumps(self).decode('UTF-8') @classmethod def from_csv(
diff --git a/tests/units/array/test_array_from_to_json.py b/tests/units/array/test_array_from_to_json.py --- a/tests/units/array/test_array_from_to_json.py +++ b/tests/units/array/test_array_from_to_json.py @@ -78,9 +78,9 @@ def _rand_vec_gen(tensor_type): return vec v = generate_docs(tensor_type) - bytes_ = v.to_json() + json_str = v.to_json() - v_after = DocVec[v.doc_type].from_json(bytes_, tensor_type=tensor_type) + v_after = DocVec[v.doc_type].from_json(json_str, tensor_type=tensor_type) assert v_after.tensor_type == v.tensor_type assert set(v_after._storage.columns.keys()) == set(v._storage.columns.keys()) @@ -125,9 +125,9 @@ class MyDoc(BaseDoc): return vec v = generate_docs() - bytes_ = v.to_json() + json_str = v.to_json() - v_after = DocVec[v.doc_type].from_json(bytes_, tensor_type=TensorFlowTensor) + v_after = DocVec[v.doc_type].from_json(json_str, tensor_type=TensorFlowTensor) assert v_after.tensor_type == v.tensor_type assert set(v_after._storage.columns.keys()) == set(v._storage.columns.keys())
Inconsistent `to_json()` return type ### Initial Checks - [X] I have read and followed [the docs](https://docs.docarray.org/) and still think this is a bug ### Description `to_json()` returns a `str` for models inherited from `BaseDoc`, whereas it is `bytes` for `DocList` ### Example Code ```Python from docarray import BaseDoc, DocList class MyModel(BaseDoc): text: str print(type(MyModel(text="abc").to_json())) # <class 'str'> print(type(DocList[MyModel]([MyModel(text="abc")]).to_json())) # <class 'bytes'> ``` ### Docarray Version ```Text 0.37.1 ``` ### Affected Components - [ ] [Vector Database / Index](https://docs.docarray.org/user_guide/storing/docindex/) - [ ] [Representing](https://docs.docarray.org/user_guide/representing/first_step) - [X] [Sending](https://docs.docarray.org/user_guide/sending/first_step/) - [ ] [storing](https://docs.docarray.org/user_guide/storing/first_step/) - [ ] [multi modal data type](https://docs.docarray.org/data_types/first_steps/)
I will take a look
2023-09-01T11:36:39
python/python-docs-es
40
python__python-docs-es-40
[ "31" ]
3e6024957df8671964498599bf57dfcf67a499c3
diff --git a/conf.py b/conf.py --- a/conf.py +++ b/conf.py @@ -33,10 +33,34 @@ os.system('mkdir -p cpython/locales/es/') os.system('ln -nfs `pwd` cpython/locales/es/LC_MESSAGES') +os.system('ln -nfs `pwd`/CONTRIBUTING.rst cpython/Doc/CONTRIBUTING.rst') gettext_compact = False locale_dirs = ['../locales', 'cpython/locales'] # relative to the sourcedir def setup(app): + + def add_contributing_banner(app, doctree): + """ + Insert a banner at the top of the index. + + This way, we can easily communicate people to help with the translation, + pointing them to different resources. + """ + from docutils import nodes, core + + message = '¡Ayúdanos a traducir la documentación oficial de Python al Español! ' \ + f'Puedes encontrar más información en `Como contribuir </es/{version}/CONTRIBUTING.html>`_ ' \ + 'y así ayudarnos a acercar Python a más personas de habla hispana.' + + paragraph = core.publish_doctree(message)[0] + banner = nodes.warning(ids=['contributing-banner']) + banner.append(paragraph) + + for document in doctree.traverse(nodes.document): + document.insert(0, banner) + # Change the sourcedir programmatically because Read the Docs always call it with `.` app.srcdir = 'cpython/Doc' + + app.connect('doctree-read', add_contributing_banner)
Mejorar la guía de CONTRIBUTING Tenemos una pequeña guía que explica el procedimiento. Sin embargo, estaría bueno mejorarla un poco para que sea más fácil de seguir para persona que no sepan mucho de github y demás herramientas: https://github.com/raulcd/python-docs-es/blob/3.7/CONTRIBUTING.rst
Vale, anoto esto aquí para que no se me olvide pero pondré una sección específica en el contributing, donde podemos añadir, si os parece, un FAQ, o más bien frequently faced problems.... ahaha y poner si acaso las cosas que pueden ocurrir: En Mac, fallos al intentar make progress que dicen algo de un realpath son 99% posiblemente la falta de una librería, se soluciona haciendo: brew install coreutils Deberiamos añadir las herramientas para que el build pase: `powrap`, `pospell`, diccionarios, etc
2020-05-03T11:29:56
python/python-docs-es
106
python__python-docs-es-106
[ "28" ]
0dfb1d5cf1d55d9ff35a20f4abc18694071b0914
diff --git a/conf.py b/conf.py --- a/conf.py +++ b/conf.py @@ -11,7 +11,7 @@ # # This can be built locally using `sphinx-build` by running # -# $ sphinx-build -b html -n -d _build/doctrees -D language=es . _build/html +# $ sphinx-build -b html -d _build/doctrees -D language=es . _build/html import sys, os, time sys.path.append(os.path.abspath('cpython/Doc/tools/extensions')) @@ -37,6 +37,12 @@ os.system('ln -nfs `pwd` cpython/locales/es/LC_MESSAGES') +exclude_patterns = [ + # This file is not included and it not marked as :orphan: + 'distutils/_setuptools_disclaimer.rst', + 'README.rst', +] + if not os.environ.get('SPHINX_GETTEXT') == 'True': # Override all the files from ``.overrides`` directory import glob
Revisar los `:role:!key` Cuando hicimos la migración #27 aceptamos `:role:!key` como `:role:key`. La única diferencia entre ellos es que el que tiene `!` no hace un link a la referencia. Tenemos que revisar que queden consistentes nuevamente.
2020-05-07T00:36:54
python/python-docs-es
121
python__python-docs-es-121
[ "119" ]
3cef9cf7342400e6b2eab0cc4a3d6b9a3c86a9f5
diff --git a/conf.py b/conf.py --- a/conf.py +++ b/conf.py @@ -33,8 +33,6 @@ templates_path = ['cpython/Doc/tools/templates'] html_static_path = ['cpython/Doc/tools/static'] -extensions.append('sphinx_autorun') - os.system('mkdir -p cpython/locales/es/') os.system('ln -nfs `pwd` cpython/locales/es/LC_MESSAGES') @@ -107,3 +105,22 @@ def add_contributing_banner(app, doctree): app.srcdir = 'cpython/Doc' app.connect('doctree-read', add_contributing_banner) + + # Import the sphinx-autorun manually to avoid this warning + # TODO: Remove this code and use just ``extensions.append('sphinx_autorun')`` when + # that issue gets fixed + # See https://github.com/WhyNotHugo/sphinx-autorun/issues/17 + + # WARNING: the sphinx_autorun extension does not declare if it is safe for + # parallel reading, assuming it isn't - please ask the extension author to + # check and make it explicit + # WARNING: doing serial read + from sphinx_autorun import RunBlock, AutoRun + app.add_directive('runblock', RunBlock) + app.connect('builder-inited', AutoRun.builder_init) + app.add_config_value('autorun_languages', AutoRun.config, 'env') + return { + 'version': '0.1', + 'parallel_read_safe': True, + 'parallel_write_safe': True, + }
diff --git a/library/test.po b/library/test.po --- a/library/test.po +++ b/library/test.po @@ -15,7 +15,6 @@ msgstr "" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: python-doc-es\n" -"python.org)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n"
Hay un par de warnings en sphinx que rompieron el build He mergado algunas PRs y parece que el build en 3.8 se rompe al haber activado el fallo por warnings en sphinx. Si puedo luego lo miro, pero probablemente @humitos puede arreglarlo rápido.
2020-05-07T11:24:43
python/python-docs-es
254
python__python-docs-es-254
[ "61" ]
65139bafb49f8dd0198f81b530a025b7f0462c6d
diff --git a/scripts/print_percentage_library.py b/scripts/print_percentage_library.py new file mode 100755 --- /dev/null +++ b/scripts/print_percentage_library.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python + +import glob +import os + +import polib # fades + +PO_DIR = os.path.abspath( + os.path.join( + os.path.dirname(__file__), + '..', + )) + + +def main(): + for pofilename in sorted(glob.glob(PO_DIR + '**/library/*.po')): + po = polib.pofile(pofilename) + file_per = po.percent_translated() + print(f"{pofilename} ::: {file_per}%") + + +if __name__ == "__main__": + main()
Translating `library/functions.po` I will take care of this file
Done in #218 No está acabado el fichero, entiendo que la issue debería quedarse abierta hasta que lo termine no? Mañana pensaba ponerme a seguir traduciendo, ya que los días anteriores me centré en reviews. Si acaso la próxima PR que hago del fichero la dejo en draft hasta que termine, te parece bien @humitos ? Uy, perdón! Mala mía. Sí, el issue lo dejamos abierto hasta que esté terminada la tarea. Buena idea la de dejar el PR en Draft hasta que esté listo para review 👍 Puedes crear otra branch desde 3.8 (actualizada) y una nueva PR Vale perfecto, hoy traduciré algún parrafito y haré eso de dejarlo como draft. Muchas gracias!
2020-05-13T18:16:16
python/python-docs-es
760
python__python-docs-es-760
[ "746" ]
2c53eb706cb6d6bbd516970fd69d8ab189f06198
diff --git a/scripts/create_issue.py b/scripts/create_issue.py --- a/scripts/create_issue.py +++ b/scripts/create_issue.py @@ -17,7 +17,7 @@ g = Github(os.environ.get('GITHUB_TOKEN')) -repo = g.get_repo('PyCampES/python-docs-es') +repo = g.get_repo('python/python-docs-es') issues = repo.get_issues(state='all')
diff --git a/library/test.po b/library/test.po --- a/library/test.po +++ b/library/test.po @@ -3,7 +3,7 @@ # Maintained by the python-doc-es workteam. # [email protected] / # https://mail.python.org/mailman3/lists/docs-es.python.org/ -# Check https://github.com/PyCampES/python-docs-es/blob/3.8/TRANSLATORS to +# Check https://github.com/python/python-docs-es/blob/3.8/TRANSLATORS to # get the list of volunteers # msgid ""
Reemplazar 'PyCampES/python-docs-es' en links a repositorio 'python/python-docs-es' Parece que se están realizando redirecciones en links del repositorio `PyCampES/python-docs-es` a `python/python-docs-es`. Me imagino que `PyCampES` sería la antigua organización que administraba este proyecto. No vendría mal reemplazar los links para que apunten a este repositorio y nos ahorramos la redirección. Lo haría en un momento, pero prefiero abrir este issue para asegurarme que no se han mantenido así por alguna razón.
2020-09-17T14:00:31
python/python-docs-es
1,000
python__python-docs-es-1000
[ "513" ]
1907e6a2696adc941cf95a1e34a3804d17cf027e
diff --git a/conf.py b/conf.py --- a/conf.py +++ b/conf.py @@ -42,8 +42,9 @@ # Extend settings from upstream _exclude_patterns = [ - # This file is not included and it not marked as :orphan: - '*/distutils/_setuptools_disclaimer.rst', + # This file is not included and it's not marked as :orphan: + 'distutils/_setuptools_disclaimer.rst', + 'cpython/Doc/distutils/_setuptools_disclaimer.rst', ] if 'exclude_patterns' in globals(): exclude_patterns += _exclude_patterns
Translate `library/signal.po` This needs to reach 100% translated. Current stats for `library/signal.po`: - Fuzzy: 0 - Percent translated: 0% - Entries: 0 / 119 - Untranslated: 119 Please, comment here if you want this file to be assigned to you and an member will assign it to you as soon as possible, so you can start working on it. Remember to follow the steps in our [Contributing Guide](https://python-docs-es.readthedocs.io/page/CONTRIBUTING.html).
Quiero traducir este.. me lo podría asignar? éxito con la traducción! :tada: @VladimirGonzalez te podemos ayudar en algo para poder continuar con este archivo? Si no tienes tiempo, lo podemos dejar libre para que otra persona continué con el. Hola, buenos días. ¿Me podríais asignar esta tarea por favor? Claro @alochimpasplum, éxito con la traducción! Recuerda que estamos en el discord de HacktoberfestES si es que te inscribiste, si no, tenemos un grupo de telegram en caso de preguntas. Gracias! Más tarde me meto al discord ☺
2020-10-07T15:32:43
python/python-docs-es
1,201
python__python-docs-es-1201
[ "1200" ]
da32ddde49e611ab169433af16c501a19bf1f216
diff --git a/conf.py b/conf.py --- a/conf.py +++ b/conf.py @@ -69,10 +69,16 @@ _stdauthor, 'manual'), ] -extensions.extend([ - 'sphinx_tabs.tabs', - 'sphinxemoji.sphinxemoji', -]) +try: + extensions.extend([ + 'sphinx_tabs.tabs', + 'sphinxemoji.sphinxemoji', + ]) +except NameError: + extensions = [ + 'sphinx_tabs.tabs', + 'sphinxemoji.sphinxemoji', + ] def setup(app):
readthedocs: 'extensions' is not defined Por alguna razón, hemos encontrado https://github.com/UPC/ravada/issues/890 en la CI de readthedocs, y actualmente los builds tienen el siguiente error: ``` % python -m sphinx -T -j auto -E -b html -d _build/doctrees -D language=es . _build/html Running Sphinx v2.2.0 Traceback (most recent call last): File "/home/cmaureir/repos/python-docs-es-admin/venv/lib/python3.9/site-packages/sphinx/config.py", line 361, in eval_config_file execfile_(filename, namespace) File "/home/cmaureir/repos/python-docs-es-admin/venv/lib/python3.9/site-packages/sphinx/util/pycompat.py", line 81, in execfile_ exec(code, _globals) File "/home/cmaureir/repos/python-docs-es-admin/conf.py", line 22, in <module> from conf import * File "/home/cmaureir/repos/python-docs-es-admin/conf.py", line 72, in <module> if extensions: NameError: name 'extensions' is not defined During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/cmaureir/repos/python-docs-es-admin/venv/lib/python3.9/site-packages/sphinx/cmd/build.py", line 272, in build_main app = Sphinx(args.sourcedir, args.confdir, args.outputdir, File "/home/cmaureir/repos/python-docs-es-admin/venv/lib/python3.9/site-packages/sphinx/application.py", line 210, in __init__ self.config = Config.read(self.confdir, confoverrides or {}, self.tags) File "/home/cmaureir/repos/python-docs-es-admin/venv/lib/python3.9/site-packages/sphinx/config.py", line 196, in read namespace = eval_config_file(filename, tags) File "/home/cmaureir/repos/python-docs-es-admin/venv/lib/python3.9/site-packages/sphinx/config.py", line 371, in eval_config_file raise ConfigError(msg % traceback.format_exc()) sphinx.errors.ConfigError: There is a programmable error in your configuration file: Traceback (most recent call last): File "/home/cmaureir/repos/python-docs-es-admin/venv/lib/python3.9/site-packages/sphinx/config.py", line 361, in eval_config_file execfile_(filename, namespace) File "/home/cmaureir/repos/python-docs-es-admin/venv/lib/python3.9/site-packages/sphinx/util/pycompat.py", line 81, in execfile_ exec(code, _globals) File "/home/cmaureir/repos/python-docs-es-admin/conf.py", line 22, in <module> from conf import * File "/home/cmaureir/repos/python-docs-es-admin/conf.py", line 72, in <module> if extensions: NameError: name 'extensions' is not defined Configuration error: There is a programmable error in your configuration file: Traceback (most recent call last): File "/home/cmaureir/repos/python-docs-es-admin/venv/lib/python3.9/site-packages/sphinx/config.py", line 361, in eval_config_file execfile_(filename, namespace) File "/home/cmaureir/repos/python-docs-es-admin/venv/lib/python3.9/site-packages/sphinx/util/pycompat.py", line 81, in execfile_ exec(code, _globals) File "/home/cmaureir/repos/python-docs-es-admin/conf.py", line 22, in <module> from conf import * File "/home/cmaureir/repos/python-docs-es-admin/conf.py", line 72, in <module> if extensions: NameError: name 'extensions' is not defined ``` Localmente `extensions` está definido, pero por alguna razón no en el CI de readthedocs.
2021-01-10T20:58:27
python/python-docs-es
1,269
python__python-docs-es-1269
[ "1175" ]
5839b1171c5a225ba7ab71342c054447a05bd91c
diff --git a/scripts/completed_files.py b/scripts/completed_files.py old mode 100644 new mode 100755 diff --git a/scripts/print_percentage.py b/scripts/print_percentage.py old mode 100644 new mode 100755
Translate 'whatsnew/2.3.po' This needs to reach 100% translated. The rendered version of this file will be available at https://docs.python.org/es/3.8/whatsnew/2.3.html once translated. Meanwhile, the English version is shown. Current stats for `whatsnew/2.3.po`: * Fuzzy: 0 * Percent translated: 0.0% * Entries: 0 / 324 * Untranslated: 324 Please, comment here if you want this file to be assigned to you and an member will assign it to you as soon as possible, so you can start working on it. Remember to follow the steps in our [Contributing Guide](https://python-docs-es.readthedocs.io/page/CONTRIBUTING.html).
Please assign me Gracias @gomezgleonardob es bastante largo, asi que mucho éxito! @gomezgleonardob ¿has podido traducir algunas entradas? Si es así, puedes subirlas asi vamos finalizando el archivo.
2021-08-07T10:28:43
python/python-docs-es
1,712
python__python-docs-es-1712
[ "1455" ]
af0d3fb61ff261636b6976bad8e1808e4474a810
diff --git a/scripts/translate.py b/scripts/translate.py --- a/scripts/translate.py +++ b/scripts/translate.py @@ -42,6 +42,7 @@ ":program:`[^`]+`", ":keyword:`[^`]+`", ":RFC:`[^`]+`", + ":rfc:`[^`]+`", ":doc:`[^`]+`", "``[^`]+``", "`[^`]+`__",
Translate 'library/base64.po' This needs to reach 100% translated. The rendered version of this file will be available at https://docs.python.org/es/3.10/library/base64.html once translated. Meanwhile, the English version is shown. Current stats for `library/base64.po`: * Fuzzy: 4 * Percent translated: 90.9% * Entries: 50 / 55 * Untranslated: 5 Please, comment here if you want this file to be assigned to you and an member will assign it to you as soon as possible, so you can start working on it. Remember to follow the steps in our [Contributing Guide](https://python-docs-es.readthedocs.io/page/CONTRIBUTING.html).
2021-12-12T18:01:19
python/python-docs-es
1,714
python__python-docs-es-1714
[ "1454" ]
af0d3fb61ff261636b6976bad8e1808e4474a810
diff --git a/scripts/translate.py b/scripts/translate.py --- a/scripts/translate.py +++ b/scripts/translate.py @@ -46,8 +46,8 @@ "``[^`]+``", "`[^`]+`__", "`[^`]+`_", - "\*\*.+\*\*", # bold text between ** - "\*.+\*", # italic text between * + "\*\*[^\*]+\*\*", # bold text between ** + "\*[^\*]+\*", # italic text between * ] _exps = [re.compile(e) for e in _patterns]
Translate 'library/http.server.po' This needs to reach 100% translated. The rendered version of this file will be available at https://docs.python.org/es/3.10/library/http.server.html once translated. Meanwhile, the English version is shown. Current stats for `library/http.server.po`: * Fuzzy: 4 * Percent translated: 97.8% * Entries: 87 / 89 * Untranslated: 2 Please, comment here if you want this file to be assigned to you and an member will assign it to you as soon as possible, so you can start working on it. Remember to follow the steps in our [Contributing Guide](https://python-docs-es.readthedocs.io/page/CONTRIBUTING.html).
2021-12-12T18:04:24
python/python-docs-es
1,762
python__python-docs-es-1762
[ "1743" ]
cdae024bedd7192d5277e042ce02fbd0ba916fb7
diff --git a/scripts/translate.py b/scripts/translate.py --- a/scripts/translate.py +++ b/scripts/translate.py @@ -44,6 +44,8 @@ ":RFC:`[^`]+`", ":rfc:`[^`]+`", ":doc:`[^`]+`", + ":manpage:`[^`]+`", + ":sup:`[^`]+`", "``[^`]+``", "`[^`]+`__", "`[^`]+`_",
Translate 'library/os.po' This needs to reach 100% translated. The rendered version of this file will be available at https://docs.python.org/es/3.10/library/os.html once translated. Meanwhile, the English version is shown. Current stats for `library/os.po`: * Fuzzy: 27 * Percent translated: 94.8% * Entries: 804 / 848 * Untranslated: 44 Please, comment here if you want this file to be assigned to you and an member will assign it to you as soon as possible, so you can start working on it. Remember to follow the steps in our [Contributing Guide](https://python-docs-es.readthedocs.io/page/CONTRIBUTING.html).
2021-12-15T11:08:31
python/python-docs-es
1,787
python__python-docs-es-1787
[ "1392" ]
716993591bf00f1bcb487c1649dda5f1411b50ef
diff --git a/scripts/translate.py b/scripts/translate.py --- a/scripts/translate.py +++ b/scripts/translate.py @@ -44,6 +44,7 @@ ":RFC:`[^`]+`", ":rfc:`[^`]+`", ":doc:`[^`]+`", + ":source:`[^`]+`", ":manpage:`[^`]+`", ":sup:`[^`]+`", "``[^`]+``",
Translate 'using/unix.po' This needs to reach 100% translated. The rendered version of this file will be available at https://docs.python.org/es/3.10/using/unix.html once translated. Meanwhile, the English version is shown. Current stats for `using/unix.po`: * Fuzzy: 1 * Percent translated: 88.9% * Entries: 40 / 45 * Untranslated: 5 Please, comment here if you want this file to be assigned to you and an member will assign it to you as soon as possible, so you can start working on it. Remember to follow the steps in our [Contributing Guide](https://python-docs-es.readthedocs.io/page/CONTRIBUTING.html).
Please assign me :) todo tuyo :tada: @macagua te puedo ayudar con algo? tomando esta issue por inactividad, recuerda que puedes buscar issues abiertas sin problema cuando tengas tiempo!
2021-12-30T20:03:05
microsoft/botbuilder-python
175
microsoft__botbuilder-python-175
[ "162" ]
64277081e5f2fb734b1a53ca579abdca0b0509ce
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py b/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py --- a/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py +++ b/libraries/botbuilder-ai/botbuilder/ai/qna/qnamaker.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from aiohttp import ClientSession, ClientTimeout +from aiohttp import ClientSession, ClientTimeout, ClientResponse from botbuilder.schema import Activity from botbuilder.core import BotTelemetryClient, NullTelemetryClient, TurnContext @@ -115,7 +115,7 @@ async def on_qna_result( measurements = event_data.metrics ) - def fill_qna_event( + async def fill_qna_event( self, query_results: [QueryResult], turn_context: TurnContext, @@ -154,11 +154,11 @@ def fill_qna_event( QnATelemetryConstants.matched_question_property: json.dumps(query_result.questions), QnATelemetryConstants.question_id_property: str(query_result.id), QnATelemetryConstants.answer_property: query_result.answer, - QnATelemetryConstants.score_metric: query_result.score, QnATelemetryConstants.article_found_property: 'true' } - properties.update(result_properties) + + metrics[QnATelemetryConstants.score_metric] = query_result.score else: no_match_properties = { QnATelemetryConstants.matched_question_property : 'No Qna Question matched', @@ -198,6 +198,8 @@ async def get_answers( self._validate_options(hydrated_options) result = await self._query_qna_service(context, hydrated_options) + + await self.on_qna_result(result, context, telemetry_properties, telemetry_metrics) await self._emit_trace_info(context, result, hydrated_options) @@ -298,7 +300,9 @@ async def _emit_trace_info(self, turn_context: TurnContext, result: [QueryResult await turn_context.send_activity(trace_activity) async def _format_qna_result(self, result, options: QnAMakerOptions) -> [QueryResult]: - json_res = await result.json() + json_res = result + if isinstance(result, ClientResponse): + json_res = await result.json() answers_within_threshold = [ { **answer,'score': answer['score']/100 } @@ -316,7 +320,7 @@ async def _format_qna_result(self, result, options: QnAMakerOptions) -> [QueryRe answers_as_query_results = list(map(lambda answer: QueryResult(**answer), sorted_answers)) return answers_as_query_results - + def _get_headers(self): headers = { 'Content-Type': 'application/json', diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/query_result.py b/libraries/botbuilder-ai/botbuilder/ai/qna/query_result.py --- a/libraries/botbuilder-ai/botbuilder/ai/qna/query_result.py +++ b/libraries/botbuilder-ai/botbuilder/ai/qna/query_result.py @@ -5,7 +5,7 @@ class QueryResult: def __init__(self, - questions: str, + questions: [str], answer: str, score: float, metadata: [Metadata], @@ -16,7 +16,7 @@ def __init__(self, self.questions = questions, self.answer = answer, self.score = score, - self.metadata = Metadata, + self.metadata = list(map(lambda meta: Metadata(**meta), metadata)), self.source = source self.id = id
diff --git a/libraries/botbuilder-ai/tests/qna/test_qna.py b/libraries/botbuilder-ai/tests/qna/test_qna.py --- a/libraries/botbuilder-ai/tests/qna/test_qna.py +++ b/libraries/botbuilder-ai/tests/qna/test_qna.py @@ -5,11 +5,11 @@ import aiounittest, unittest, requests from os import path from requests.models import Response -from typing import List, Tuple +from typing import List, Tuple, Dict, Union from uuid import uuid4 from unittest.mock import Mock, patch, MagicMock from asyncio import Future -from aiohttp import ClientSession, ClientTimeout +from aiohttp import ClientSession, ClientTimeout, ClientResponse from botbuilder.ai.qna import Metadata, QnAMakerEndpoint, QnAMaker, QnAMakerOptions, QnATelemetryConstants, QueryResult from botbuilder.core import BotAdapter, BotTelemetryClient, NullTelemetryClient, TurnContext @@ -36,7 +36,6 @@ class QnaApplicationTest(aiounittest.AsyncTestCase): tests_endpoint = QnAMakerEndpoint(_knowledge_base_id, _endpoint_key, _host) - def test_qnamaker_construction(self): # Arrange endpoint = self.tests_endpoint @@ -161,19 +160,12 @@ async def test_returns_answer(self): response_path ) - first_answer = result['answers'][0] - - # If question yields no questions in KB - # QnAMaker v4.0 API returns 'answer': 'No good match found in KB.' and questions: [] - no_ans_found_in_kb = False - if len(result['answers']) and first_answer['score'] == 0: - no_ans_found_in_kb = True + first_answer = result[0] #Assert self.assertIsNotNone(result) - self.assertEqual(1, len(result['answers'])) - self.assertTrue(question in first_answer['questions'] or no_ans_found_in_kb) - self.assertEqual('BaseCamp: You can use a damp rag to clean around the Power Pack', first_answer['answer']) + self.assertEqual(1, len(result)) + self.assertEqual('BaseCamp: You can use a damp rag to clean around the Power Pack', first_answer.answer[0]) async def test_returns_answer_using_options(self): # Arrange @@ -195,19 +187,18 @@ async def test_returns_answer_using_options(self): options=options ) - first_answer = result['answers'][0] + first_answer = result[0] has_at_least_1_ans = True - first_metadata = first_answer['metadata'][0] + first_metadata = first_answer.metadata[0][0] # Assert self.assertIsNotNone(result) - self.assertEqual(has_at_least_1_ans, len(result) >= 1 and len(result) <= options.top) - self.assertTrue(question in first_answer['questions']) - self.assertTrue(first_answer['answer']) - self.assertEqual('is a movie', first_answer['answer']) - self.assertTrue(first_answer['score'] >= options.score_threshold) - self.assertEqual('movie', first_metadata['name']) - self.assertEqual('disney', first_metadata['value']) + self.assertEqual(has_at_least_1_ans, len(result) >= 1) + self.assertTrue(first_answer.answer[0]) + self.assertEqual('is a movie', first_answer.answer[0]) + self.assertTrue(first_answer.score[0] >= options.score_threshold) + self.assertEqual('movie', first_metadata.name) + self.assertEqual('disney', first_metadata.value) async def test_trace_test(self): activity = Activity( @@ -222,51 +213,340 @@ async def test_trace_test(self): qna = QnAMaker(QnaApplicationTest.tests_endpoint) context = TestContext(activity) - response = Mock(spec=Response) - response.status_code = 200 - response.headers = {} - response.reason = '' - - with patch('aiohttp.ClientSession.post', return_value=response): - with patch('botbuilder.ai.qna.QnAMaker._query_qna_service', return_value=aiounittest.futurized(response_json)): - result = await qna.get_answers(context) - - qna_trace_activities = list(filter(lambda act: act.type == 'trace' and act.name == 'QnAMaker', context.sent)) - trace_activity = qna_trace_activities[0] - - self.assertEqual('trace', trace_activity.type) - self.assertEqual('QnAMaker', trace_activity.name) - self.assertEqual('QnAMaker Trace', trace_activity.label) - self.assertEqual('https://www.qnamaker.ai/schemas/trace', trace_activity.value_type) - self.assertEqual(True, hasattr(trace_activity, 'value')) - self.assertEqual(True, hasattr(trace_activity.value, 'message')) - self.assertEqual(True, hasattr(trace_activity.value, 'query_results')) - self.assertEqual(True, hasattr(trace_activity.value, 'score_threshold')) - self.assertEqual(True, hasattr(trace_activity.value, 'top')) - self.assertEqual(True, hasattr(trace_activity.value, 'strict_filters')) - self.assertEqual(self._knowledge_base_id, trace_activity.value.knowledge_base_id[0]) - - return result + + with patch('aiohttp.ClientSession.post', return_value=aiounittest.futurized(response_json)): + result = await qna.get_answers(context) + + qna_trace_activities = list(filter(lambda act: act.type == 'trace' and act.name == 'QnAMaker', context.sent)) + trace_activity = qna_trace_activities[0] + + self.assertEqual('trace', trace_activity.type) + self.assertEqual('QnAMaker', trace_activity.name) + self.assertEqual('QnAMaker Trace', trace_activity.label) + self.assertEqual('https://www.qnamaker.ai/schemas/trace', trace_activity.value_type) + self.assertEqual(True, hasattr(trace_activity, 'value')) + self.assertEqual(True, hasattr(trace_activity.value, 'message')) + self.assertEqual(True, hasattr(trace_activity.value, 'query_results')) + self.assertEqual(True, hasattr(trace_activity.value, 'score_threshold')) + self.assertEqual(True, hasattr(trace_activity.value, 'top')) + self.assertEqual(True, hasattr(trace_activity.value, 'strict_filters')) + self.assertEqual(self._knowledge_base_id, trace_activity.value.knowledge_base_id[0]) + + return result async def test_returns_answer_with_timeout(self): question: str = 'how do I clean the stove?' options = QnAMakerOptions(timeout=999999) qna = QnAMaker(QnaApplicationTest.tests_endpoint, options) context = QnaApplicationTest._get_context(question, TestAdapter()) - response = Mock(spec=Response) - response.status_code = 200 - response.headers = {} - response.reason = '' response_json = QnaApplicationTest._get_json_for_file('ReturnsAnswer.json') - with patch('aiohttp.ClientSession.post', return_value=response): - with patch('botbuilder.ai.qna.QnAMaker._query_qna_service', return_value=aiounittest.futurized(response_json)): - result = await qna.get_answers(context, options) - - self.assertIsNotNone(result) - self.assertEqual(options.timeout, qna._options.timeout) + with patch('aiohttp.ClientSession.post', return_value=aiounittest.futurized(response_json)): + result = await qna.get_answers(context, options) + + self.assertIsNotNone(result) + self.assertEqual(options.timeout, qna._options.timeout) + + async def test_telemetry_returns_answer(self): + # Arrange + question: str = 'how do I clean the stove?' + response_json = QnaApplicationTest._get_json_for_file('ReturnsAnswer.json') + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = True + context = QnaApplicationTest._get_context(question, TestAdapter()) + qna = QnAMaker( + QnaApplicationTest.tests_endpoint, + telemetry_client=telemetry_client, + log_personal_information=log_personal_information + ) + + # Act + with patch('aiohttp.ClientSession.post', return_value = aiounittest.futurized(response_json)): + results = await qna.get_answers(context) + + telemetry_args = telemetry_client.track_event.call_args_list[0][1] + telemetry_properties = telemetry_args['properties'] + telemetry_metrics = telemetry_args['measurements'] + number_of_args = len(telemetry_args) + first_answer = telemetry_args['properties'][QnATelemetryConstants.answer_property][0] + expected_answer = 'BaseCamp: You can use a damp rag to clean around the Power Pack' + + # Assert - Check Telemetry logged. + self.assertEqual(1, telemetry_client.track_event.call_count) + self.assertEqual(3, number_of_args) + self.assertEqual('QnaMessage', telemetry_args['name']) + self.assertTrue('answer' in telemetry_properties) + self.assertTrue('knowledgeBaseId' in telemetry_properties) + self.assertTrue('matchedQuestion' in telemetry_properties) + self.assertTrue('question' in telemetry_properties) + self.assertTrue('questionId' in telemetry_properties) + self.assertTrue('articleFound' in telemetry_properties) + self.assertEqual(expected_answer, first_answer) + self.assertTrue('score' in telemetry_metrics) + self.assertEqual(1, telemetry_metrics['score'][0]) + + # Assert - Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer[0]) + self.assertEqual('Editorial', results[0].source) + + async def test_telemetry_pii(self): + # Arrange + question: str = 'how do I clean the stove?' + response_json = QnaApplicationTest._get_json_for_file('ReturnsAnswer.json') + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = False + context = QnaApplicationTest._get_context(question, TestAdapter()) + qna = QnAMaker( + QnaApplicationTest.tests_endpoint, + telemetry_client=telemetry_client, + log_personal_information=log_personal_information + ) + # Act + with patch('aiohttp.ClientSession.post', return_value = aiounittest.futurized(response_json)): + results = await qna.get_answers(context) + + telemetry_args = telemetry_client.track_event.call_args_list[0][1] + telemetry_properties = telemetry_args['properties'] + telemetry_metrics = telemetry_args['measurements'] + number_of_args = len(telemetry_args) + first_answer = telemetry_args['properties'][QnATelemetryConstants.answer_property][0] + expected_answer = 'BaseCamp: You can use a damp rag to clean around the Power Pack' + + # Assert - Validate PII properties not logged. + self.assertEqual(1, telemetry_client.track_event.call_count) + self.assertEqual(3, number_of_args) + self.assertEqual('QnaMessage', telemetry_args['name']) + self.assertTrue('answer' in telemetry_properties) + self.assertTrue('knowledgeBaseId' in telemetry_properties) + self.assertTrue('matchedQuestion' in telemetry_properties) + self.assertTrue('question' not in telemetry_properties) + self.assertTrue('questionId' in telemetry_properties) + self.assertTrue('articleFound' in telemetry_properties) + self.assertEqual(expected_answer, first_answer) + self.assertTrue('score' in telemetry_metrics) + self.assertEqual(1, telemetry_metrics['score'][0]) + + # Assert - Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer[0]) + self.assertEqual('Editorial', results[0].source) + + async def test_telemetry_override(self): + # Arrange + question: str = 'how do I clean the stove?' + response_json = QnaApplicationTest._get_json_for_file('ReturnsAnswer.json') + context = QnaApplicationTest._get_context(question, TestAdapter()) + options = QnAMakerOptions(top=1) + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = False + + # Act - Override the QnAMaker object to log custom stuff and honor params passed in. + telemetry_properties: Dict[str, str] = { 'id': 'MyId' } + qna = QnaApplicationTest.OverrideTelemetry( + QnaApplicationTest.tests_endpoint, + options, + None, + telemetry_client, + log_personal_information + ) + with patch('aiohttp.ClientSession.post', return_value = aiounittest.futurized(response_json)): + results = await qna.get_answers(context, options, telemetry_properties) + + telemetry_args = telemetry_client.track_event.call_args_list + first_call_args = telemetry_args[0][0] + first_call_properties = first_call_args[1] + second_call_args = telemetry_args[1][0] + second_call_properties = second_call_args[1] + expected_answer = 'BaseCamp: You can use a damp rag to clean around the Power Pack' + + # Assert + self.assertEqual(2, telemetry_client.track_event.call_count) + self.assertEqual(2, len(first_call_args)) + self.assertEqual('QnaMessage', first_call_args[0]) + self.assertEqual(2, len(first_call_properties)) + self.assertTrue('my_important_property' in first_call_properties) + self.assertEqual('my_important_value', first_call_properties['my_important_property']) + self.assertTrue('id' in first_call_properties) + self.assertEqual('MyId', first_call_properties['id']) + + self.assertEqual('my_second_event', second_call_args[0]) + self.assertTrue('my_important_property2' in second_call_properties) + self.assertEqual('my_important_value2', second_call_properties['my_important_property2']) + + # Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer[0]) + self.assertEqual('Editorial', results[0].source) + + async def test_telemetry_additional_props_metrics(self): + # Arrange + question: str = 'how do I clean the stove?' + response_json = QnaApplicationTest._get_json_for_file('ReturnsAnswer.json') + context = QnaApplicationTest._get_context(question, TestAdapter()) + options = QnAMakerOptions(top=1) + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = False + # Act + with patch('aiohttp.ClientSession.post', return_value = aiounittest.futurized(response_json)): + qna = QnAMaker(QnaApplicationTest.tests_endpoint, options, None, telemetry_client, log_personal_information) + telemetry_properties: Dict[str, str] = { 'my_important_property': 'my_important_value' } + telemetry_metrics: Dict[str, float] = { 'my_important_metric': 3.14159 } + + results = await qna.get_answers(context, None, telemetry_properties, telemetry_metrics) + + # Assert - Added properties were added. + telemetry_args = telemetry_client.track_event.call_args_list[0][1] + telemetry_properties = telemetry_args['properties'] + expected_answer = 'BaseCamp: You can use a damp rag to clean around the Power Pack' + + self.assertEqual(1, telemetry_client.track_event.call_count) + self.assertEqual(3, len(telemetry_args)) + self.assertEqual('QnaMessage', telemetry_args['name']) + self.assertTrue('knowledgeBaseId' in telemetry_properties) + self.assertTrue('question' not in telemetry_properties) + self.assertTrue('matchedQuestion' in telemetry_properties) + self.assertTrue('questionId' in telemetry_properties) + self.assertTrue('answer' in telemetry_properties) + self.assertTrue(expected_answer, telemetry_properties['answer'][0]) + self.assertTrue('my_important_property' in telemetry_properties) + self.assertEqual('my_important_value', telemetry_properties['my_important_property']) + + tracked_metrics = telemetry_args['measurements'] + + self.assertEqual(2, len(tracked_metrics)) + self.assertTrue('score' in tracked_metrics) + self.assertTrue('my_important_metric' in tracked_metrics) + self.assertEqual(3.14159, tracked_metrics['my_important_metric']) + + # Assert - Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer[0]) + self.assertEqual('Editorial', results[0].source) + + async def test_telemetry_additional_props_override(self): + question: str = 'how do I clean the stove?' + response_json = QnaApplicationTest._get_json_for_file('ReturnsAnswer.json') + context = QnaApplicationTest._get_context(question, TestAdapter()) + options = QnAMakerOptions(top=1) + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = False + + # Act - Pass in properties during QnA invocation that override default properties + # NOTE: We are invoking this with PII turned OFF, and passing a PII property (originalQuestion). + qna = QnAMaker(QnaApplicationTest.tests_endpoint, options, None, telemetry_client, log_personal_information) + telemetry_properties = { + 'knowledge_base_id': 'my_important_value', + 'original_question': 'my_important_value2' + } + telemetry_metrics = { + 'score': 3.14159 + } + + with patch('aiohttp.ClientSession.post', return_value = aiounittest.futurized(response_json)): + results = await qna.get_answers(context, None, telemetry_properties, telemetry_metrics) + + # Assert - Added properties were added. + tracked_args = telemetry_client.track_event.call_args_list[0][1] + tracked_properties = tracked_args['properties'] + expected_answer = 'BaseCamp: You can use a damp rag to clean around the Power Pack' + tracked_metrics = tracked_args['measurements'] + + self.assertEqual(1, telemetry_client.track_event.call_count) + self.assertEqual(3, len(tracked_args)) + self.assertEqual('QnaMessage', tracked_args['name']) + self.assertTrue('knowledge_base_id' in tracked_properties) + self.assertEqual('my_important_value', tracked_properties['knowledge_base_id']) + self.assertTrue('original_question' in tracked_properties) + self.assertTrue('matchedQuestion' in tracked_properties) + self.assertEqual('my_important_value2', tracked_properties['original_question']) + self.assertTrue('question' not in tracked_properties) + self.assertTrue('questionId' in tracked_properties) + self.assertTrue('answer' in tracked_properties) + self.assertEqual(expected_answer, tracked_properties['answer'][0]) + self.assertTrue('my_important_property' not in tracked_properties) + self.assertEqual(1, len(tracked_metrics)) + self.assertTrue('score' in tracked_metrics) + self.assertEqual(3.14159, tracked_metrics['score']) + + # Assert - Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer[0]) + self.assertEqual('Editorial', results[0].source) + + async def test_telemetry_fill_props_override(self): + # Arrange + question: str = 'how do I clean the stove?' + response_json = QnaApplicationTest._get_json_for_file('ReturnsAnswer.json') + context: TurnContext = QnaApplicationTest._get_context(question, TestAdapter()) + options = QnAMakerOptions(top=1) + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = False + + # Act - Pass in properties during QnA invocation that override default properties + # In addition Override with derivation. This presents an interesting question of order of setting properties. + # If I want to override "originalQuestion" property: + # - Set in "Stock" schema + # - Set in derived QnAMaker class + # - Set in GetAnswersAsync + # Logically, the GetAnswersAync should win. But ultimately OnQnaResultsAsync decides since it is the last + # code to touch the properties before logging (since it actually logs the event). + qna = QnaApplicationTest.OverrideFillTelemetry( + QnaApplicationTest.tests_endpoint, + options, + None, + telemetry_client, + log_personal_information + ) + telemetry_properties: Dict[str, str] = { + 'knowledgeBaseId': 'my_important_value', + 'matchedQuestion': 'my_important_value2' + } + telemetry_metrics: Dict[str, float] = { + 'score': 3.14159 + } + + with patch('aiohttp.ClientSession.post', return_value = aiounittest.futurized(response_json)): + results = await qna.get_answers(context, None, telemetry_properties, telemetry_metrics) + + # Assert - Added properties were added. + first_call_args = telemetry_client.track_event.call_args_list[0][0] + first_properties = first_call_args[1] + expected_answer = 'BaseCamp: You can use a damp rag to clean around the Power Pack' + first_metrics = first_call_args[2] + + self.assertEqual(2, telemetry_client.track_event.call_count) + self.assertEqual(3, len(first_call_args)) + self.assertEqual('QnaMessage', first_call_args[0]) + self.assertEqual(6, len(first_properties)) + self.assertTrue('knowledgeBaseId' in first_properties) + self.assertEqual('my_important_value', first_properties['knowledgeBaseId']) + self.assertTrue('matchedQuestion' in first_properties) + self.assertEqual('my_important_value2', first_properties['matchedQuestion']) + self.assertTrue('questionId' in first_properties) + self.assertTrue('answer' in first_properties) + self.assertEqual(expected_answer, first_properties['answer'][0]) + self.assertTrue('articleFound' in first_properties) + self.assertTrue('my_important_property' in first_properties) + self.assertEqual('my_important_value', first_properties['my_important_property']) + + self.assertEqual(1, len(first_metrics)) + self.assertTrue('score' in first_metrics) + self.assertEqual(3.14159, first_metrics['score']) + + # Assert - Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer[0]) + self.assertEqual('Editorial', results[0].source) + @classmethod async def _get_service_result( @@ -281,16 +561,11 @@ async def _get_service_result( qna = QnAMaker(QnaApplicationTest.tests_endpoint) context = QnaApplicationTest._get_context(utterance, bot_adapter) - response = aiounittest.futurized(Mock(return_value=Response)) - response.status_code = 200 - response.headers = {} - response.reason = '' + with patch('aiohttp.ClientSession.post', return_value = aiounittest.futurized(response_json)): + result = await qna.get_answers(context, options) - with patch('aiohttp.ClientSession.post', return_value=response): - with patch('botbuilder.ai.qna.QnAMaker._query_qna_service', return_value=aiounittest.futurized(response_json)): - result = await qna.get_answers(context, options) - - return result + return result + @classmethod def _get_json_for_file(cls, response_file: str) -> object: @@ -304,11 +579,11 @@ def _get_json_for_file(cls, response_file: str) -> object: return response_json @staticmethod - def _get_context(utterance: str, bot_adapter: BotAdapter) -> TurnContext: + def _get_context(question: str, bot_adapter: BotAdapter) -> TurnContext: test_adapter = bot_adapter or TestAdapter() activity = Activity( type = ActivityTypes.message, - text = utterance, + text = question, conversation = ConversationAccount(), recipient = ChannelAccount(), from_property = ChannelAccount(), @@ -316,3 +591,86 @@ def _get_context(utterance: str, bot_adapter: BotAdapter) -> TurnContext: return TurnContext(test_adapter, activity) + class OverrideTelemetry(QnAMaker): + def __init__( + self, + endpoint: QnAMakerEndpoint, + options: QnAMakerOptions, + http_client: ClientSession, + telemetry_client: BotTelemetryClient, + log_personal_information: bool + ): + super().__init__( + endpoint, + options, + http_client, + telemetry_client, + log_personal_information + ) + + async def on_qna_result( + self, + query_results: [QueryResult], + context: TurnContext, + telemetry_properties: Dict[str, str] = None, + telemetry_metrics: Dict[str, float] = None + ): + properties = telemetry_properties or {} + + # get_answers overrides derived class + properties['my_important_property'] = 'my_important_value' + + # Log event + self.telemetry_client.track_event(QnATelemetryConstants.qna_message_event, properties) + + # Create 2nd event. + second_event_properties = { + 'my_important_property2': 'my_important_value2' + } + self.telemetry_client.track_event('my_second_event', second_event_properties) + + class OverrideFillTelemetry(QnAMaker): + def __init__( + self, + endpoint: QnAMakerEndpoint, + options: QnAMakerOptions, + http_client: ClientSession, + telemetry_client: BotTelemetryClient, + log_personal_information: bool + ): + super().__init__( + endpoint, + options, + http_client, + telemetry_client, + log_personal_information + ) + + async def on_qna_result( + self, + query_results: [QueryResult], + context: TurnContext, + telemetry_properties: Dict[str, str] = None, + telemetry_metrics: Dict[str, float] = None + ): + event_data = await self.fill_qna_event(query_results, context, telemetry_properties, telemetry_metrics) + + # Add my property. + event_data.properties.update({ 'my_important_property': 'my_important_value' }) + + # Log QnaMessage event. + self.telemetry_client.track_event( + QnATelemetryConstants.qna_message_event, + event_data.properties, + event_data.metrics + ) + + # Create second event. + second_event_properties: Dict[str, str] = { + 'my_important_property2': 'my_important_value2' + } + + self.telemetry_client.track_event( + 'MySecondEvent', + second_event_properties + )
More QnAMaker unit tests ...more test coverage...
2019-05-13T23:48:55
microsoft/botbuilder-python
260
microsoft__botbuilder-python-260
[ "239" ]
2dd2c2047b3514a4fbddc028d5fdb1726c1780fd
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/choice_prompt.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/choice_prompt.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/choice_prompt.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/choice_prompt.py @@ -30,28 +30,52 @@ class ChoicePrompt(Prompt): _default_choice_options: Dict[str, ChoiceFactoryOptions] = { Culture.Spanish: ChoiceFactoryOptions( - inline_separator=", ", inline_or=" o ", include_numbers=True + inline_separator=", ", + inline_or=" o ", + inline_or_more=", o ", + include_numbers=True, ), Culture.Dutch: ChoiceFactoryOptions( - inline_separator=", ", inline_or=" of ", include_numbers=True + inline_separator=", ", + inline_or=" of ", + inline_or_more=", of ", + include_numbers=True, ), Culture.English: ChoiceFactoryOptions( - inline_separator=", ", inline_or=" or ", include_numbers=True + inline_separator=", ", + inline_or=" or ", + inline_or_more=", or ", + include_numbers=True, ), Culture.French: ChoiceFactoryOptions( - inline_separator=", ", inline_or=" ou ", include_numbers=True + inline_separator=", ", + inline_or=" ou ", + inline_or_more=", ou ", + include_numbers=True, ), "de-de": ChoiceFactoryOptions( - inline_separator=", ", inline_or=" oder ", include_numbers=True + inline_separator=", ", + inline_or=" oder ", + inline_or_more=", oder ", + include_numbers=True, ), Culture.Japanese: ChoiceFactoryOptions( - inline_separator="、 ", inline_or=" または ", include_numbers=True + inline_separator="、 ", + inline_or=" または ", + inline_or_more="、 または ", + include_numbers=True, ), Culture.Portuguese: ChoiceFactoryOptions( - inline_separator=", ", inline_or=" ou ", include_numbers=True + inline_separator=", ", + inline_or=" ou ", + inline_or_more=", ou ", + include_numbers=True, ), Culture.Chinese: ChoiceFactoryOptions( - inline_separator=", ", inline_or=" 要么 ", include_numbers=True + inline_separator=", ", + inline_or=" 要么 ", + inline_or_more=", 要么 ", + include_numbers=True, ), } diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt.py @@ -2,7 +2,7 @@ # Licensed under the MIT License. import copy -from typing import Dict +from typing import Dict, List from .prompt_options import PromptOptions from .prompt_validator_context import PromptValidatorContext from ..dialog_reason import DialogReason @@ -12,7 +12,12 @@ from ..dialog_context import DialogContext from botbuilder.core.turn_context import TurnContext from botbuilder.schema import InputHints, ActivityTypes -from botbuilder.dialogs.choices import ChoiceFactory +from botbuilder.dialogs.choices import ( + Choice, + ChoiceFactory, + ChoiceFactoryOptions, + ListStyle, +) from abc import abstractmethod from botbuilder.schema import Activity @@ -142,16 +147,13 @@ async def on_recognize( ): pass - # TODO: Fix choices to use Choice object when ported. - # TODO: Fix style to use ListStyle when ported. - # TODO: Fix options to use ChoiceFactoryOptions object when ported. def append_choices( self, prompt: Activity, channel_id: str, - choices: object, - style: object, - options: object = None, + choices: List[Choice], + style: ListStyle, + options: ChoiceFactoryOptions = None, ) -> Activity: """ Helper function to compose an output activity containing a set of choices. @@ -187,23 +189,24 @@ def hero_card() -> Activity: return ChoiceFactory.hero_card(choices, text) def list_style_none() -> Activity: - activity = Activity() + activity = Activity(type=ActivityTypes.message) activity.text = text return activity def default() -> Activity: return ChoiceFactory.for_channel(channel_id, choices, text, None, options) + # Maps to values in ListStyle Enum switcher = { - # ListStyle.inline - 1: inline, - 2: list_style, - 3: suggested_action, - 4: hero_card, - 5: list_style_none, + 0: list_style_none, + 1: default, + 2: inline, + 3: list_style, + 4: suggested_action, + 5: hero_card, } - msg = switcher.get(style, default)() + msg = switcher.get(int(style.value), default)() # Update prompt with text, actions and attachments if not prompt:
diff --git a/libraries/botbuilder-dialogs/tests/test_choice_prompt.py b/libraries/botbuilder-dialogs/tests/test_choice_prompt.py --- a/libraries/botbuilder-dialogs/tests/test_choice_prompt.py +++ b/libraries/botbuilder-dialogs/tests/test_choice_prompt.py @@ -267,11 +267,8 @@ async def validator(prompt: PromptValidatorContext) -> bool: dialogs.add(choice_prompt) step1 = await adapter.send(Activity(type=ActivityTypes.message, text="Hello")) - # TODO ChoiceFactory.inline() is broken, where it only uses hard-coded English locale. - # commented out the CORRECT assertion below, until .inline() is fixed to use proper locale - # step2 = await step1.assert_reply('Please choose a color. (1) red, (2) green, o (3) blue') step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" + "Please choose a color. (1) red, (2) green, o (3) blue" ) step3 = await step2.send(_invalid_message) step4 = await step3.assert_reply("Bad input.") @@ -318,11 +315,8 @@ async def validator(prompt: PromptValidatorContext) -> bool: step1 = await adapter.send( Activity(type=ActivityTypes.message, text="Hello", locale=Culture.Spanish) ) - # TODO ChoiceFactory.inline() is broken, where it only uses hard-coded English locale. - # commented out the CORRECT assertion below, until .inline() is fixed to use proper locale - # step2 = await step1.assert_reply('Please choose a color. (1) red, (2) green, o (3) blue') step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" + "Please choose a color. (1) red, (2) green, o (3) blue" ) step3 = await step2.send(_answer_message) await step3.assert_reply("red") @@ -377,9 +371,7 @@ async def validator(prompt: PromptValidatorContext) -> bool: step3 = await step2.send(_answer_message) await step3.assert_reply("red") - async def test_should_not_render_choices_and_not_blow_up_if_choices_are_not_passed_in( - self - ): + async def test_should_not_render_choices_if_list_style_none_is_specified(self): async def exec_test(turn_context: TurnContext): dc = await dialogs.create_context(turn_context) @@ -390,7 +382,8 @@ async def exec_test(turn_context: TurnContext): prompt=Activity( type=ActivityTypes.message, text="Please choose a color." ), - choices=None, + choices=_color_choices, + style=ListStyle.none, ) await dc.prompt("prompt", options) elif results.status == DialogTurnStatus.Complete: @@ -406,18 +399,15 @@ async def exec_test(turn_context: TurnContext): dialogs = DialogSet(dialog_state) choice_prompt = ChoicePrompt("prompt") - choice_prompt.style = ListStyle.none dialogs.add(choice_prompt) step1 = await adapter.send("Hello") - await step1.assert_reply("Please choose a color.") + step2 = await step1.assert_reply("Please choose a color.") + step3 = await step2.send(_answer_message) + await step3.assert_reply("red") - # TODO to create parity with JS, need to refactor this so that it does not blow up when choices are None - # Possibly does not work due to the side effect of list styles not applying - # Note: step2 only appears to pass as ListStyle.none, probably because choices is None, and therefore appending - # nothing to the prompt text - async def test_should_not_recognize_if_choices_are_not_passed_in(self): + async def test_should_create_prompt_with_inline_choices_when_specified(self): async def exec_test(turn_context: TurnContext): dc = await dialogs.create_context(turn_context) @@ -428,7 +418,7 @@ async def exec_test(turn_context: TurnContext): prompt=Activity( type=ActivityTypes.message, text="Please choose a color." ), - choices=None, + choices=_color_choices, ) await dc.prompt("prompt", options) elif results.status == DialogTurnStatus.Complete: @@ -444,17 +434,18 @@ async def exec_test(turn_context: TurnContext): dialogs = DialogSet(dialog_state) choice_prompt = ChoicePrompt("prompt") - choice_prompt.style = ListStyle.none + choice_prompt.style = ListStyle.in_line dialogs.add(choice_prompt) step1 = await adapter.send("Hello") - step2 = await step1.assert_reply("Please choose a color.") - # TODO uncomment when styling is fixed for prompts - assertions should pass - # step3 = await step2.send('hello') - # await step3.assert_reply('Please choose a color.') + step2 = await step1.assert_reply( + "Please choose a color. (1) red, (2) green, or (3) blue" + ) + step3 = await step2.send(_answer_message) + await step3.assert_reply("red") - async def test_should_create_prompt_with_inline_choices_when_specified(self): + async def test_should_create_prompt_with_list_choices_when_specified(self): async def exec_test(turn_context: TurnContext): dc = await dialogs.create_context(turn_context) @@ -481,20 +472,20 @@ async def exec_test(turn_context: TurnContext): dialogs = DialogSet(dialog_state) choice_prompt = ChoicePrompt("prompt") - choice_prompt.style = ListStyle.in_line + choice_prompt.style = ListStyle.list_style dialogs.add(choice_prompt) step1 = await adapter.send("Hello") step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" + "Please choose a color.\n\n 1. red\n 2. green\n 3. blue" ) step3 = await step2.send(_answer_message) await step3.assert_reply("red") - # TODO fix test to actually test for list_style instead of inline - # currently bug where all styling is ignored and only does inline styling for prompts - async def test_should_create_prompt_with_list_choices_when_specified(self): + async def test_should_create_prompt_with_suggested_action_style_when_specified( + self + ): async def exec_test(turn_context: TurnContext): dc = await dialogs.create_context(turn_context) @@ -506,6 +497,43 @@ async def exec_test(turn_context: TurnContext): type=ActivityTypes.message, text="Please choose a color." ), choices=_color_choices, + style=ListStyle.suggested_action, + ) + await dc.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + choice_prompt = ChoicePrompt("prompt") + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply("Please choose a color.") + step3 = await step2.send(_answer_message) + await step3.assert_reply("red") + + async def test_should_create_prompt_with_auto_style_when_specified(self): + async def exec_test(turn_context: TurnContext): + dc = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dc.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + style=ListStyle.auto, ) await dc.prompt("prompt", options) elif results.status == DialogTurnStatus.Complete: @@ -521,14 +549,10 @@ async def exec_test(turn_context: TurnContext): dialogs = DialogSet(dialog_state) choice_prompt = ChoicePrompt("prompt") - choice_prompt.style = ListStyle.list_style dialogs.add(choice_prompt) step1 = await adapter.send("Hello") - # TODO uncomment assertion when prompt styling has been fixed - assertion should pass with list_style - # Also be sure to remove inline assertion currently being tested below - # step2 = await step1.assert_reply('Please choose a color.\n\n 1. red\n 2. green\n 3. blue') step2 = await step1.assert_reply( "Please choose a color. (1) red, (2) green, or (3) blue" )
ChoiceFactory forces usage of hardcoded ChoiceFactoryOptions; can therefore only use en-us locale ## Version python v4.4 ## Describe the bug * `ChoiceFactory.inline()` is broken, in that it does not use the passed in `options` parameter, and only uses `opt`, the hard-coded "or" separators * this in turn means that English is the only locale that prompts are able to use * also, due to https://github.com/microsoft/botbuilder-python/issues/240, we can't move away from inline styling, therefore we can't move away from `en-us` locale ## Expected behavior To use the locale specified, and not only stick to `en-us`
2019-07-16T20:52:22
microsoft/botbuilder-python
279
microsoft__botbuilder-python-279
[ "269" ]
3b2071cd757d7e20c65c76b8a434db265a32fb30
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/number_prompt.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/number_prompt.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/number_prompt.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/number_prompt.py @@ -1,18 +1,29 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Dict +from typing import Callable, Dict + +from babel.numbers import parse_decimal from recognizers_number import recognize_number +from recognizers_text import Culture, ModelResult + from botbuilder.core.turn_context import TurnContext from botbuilder.schema import ActivityTypes -from .prompt import Prompt + +from .prompt import Prompt, PromptValidatorContext from .prompt_options import PromptOptions from .prompt_recognizer_result import PromptRecognizerResult class NumberPrompt(Prompt): - # TODO: PromptValidator - def __init__(self, dialog_id: str, validator: object, default_locale: str): + # TODO: PromptValidator needs to be fixed + # Does not accept answer as intended (times out) + def __init__( + self, + dialog_id: str, + validator: Callable[[PromptValidatorContext], bool] = None, + default_locale: str = None, + ): super(NumberPrompt, self).__init__(dialog_id, validator) self.default_locale = default_locale @@ -30,9 +41,8 @@ async def on_prompt( if is_retry and options.retry_prompt is not None: turn_context.send_activity(options.retry_prompt) - else: - if options.prompt is not None: - await turn_context.send_activity(options.prompt) + elif options.prompt is not None: + await turn_context.send_activity(options.prompt) async def on_recognize( self, @@ -46,17 +56,25 @@ async def on_recognize( result = PromptRecognizerResult() if turn_context.activity.type == ActivityTypes.message: message = turn_context.activity + culture = self._get_culture(turn_context) + results: [ModelResult] = recognize_number(message.text, culture) - # TODO: Fix constant English with correct constant from text recognizer - culture = ( - turn_context.activity.locale - if turn_context.activity.locale is not None - else "English" - ) - - results = recognize_number(message.text, culture) if results: result.succeeded = True - result.value = results[0].resolution["value"] + result.value = parse_decimal( + results[0].resolution["value"], locale=culture.replace("-", "_") + ) return result + + def _get_culture(self, turn_context: TurnContext): + culture = ( + turn_context.activity.locale + if turn_context.activity.locale + else self.default_locale + ) + + if not culture: + culture = Culture.English + + return culture diff --git a/libraries/botbuilder-dialogs/setup.py b/libraries/botbuilder-dialogs/setup.py --- a/libraries/botbuilder-dialogs/setup.py +++ b/libraries/botbuilder-dialogs/setup.py @@ -12,6 +12,7 @@ "recognizers-text-choice>=1.0.1a0", "grapheme>=0.5.0", "emoji>=0.5.2", + "babel>=2.7.0", "botbuilder-schema>=4.4.0b1", "botframework-connector>=4.4.0b1", "botbuilder-core>=4.4.0b1",
diff --git a/libraries/botbuilder-dialogs/tests/test_number_prompt.py b/libraries/botbuilder-dialogs/tests/test_number_prompt.py --- a/libraries/botbuilder-dialogs/tests/test_number_prompt.py +++ b/libraries/botbuilder-dialogs/tests/test_number_prompt.py @@ -1,7 +1,16 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +from typing import Callable + import aiounittest -from botbuilder.dialogs.prompts import NumberPrompt, PromptOptions +from recognizers_text import Culture + +from botbuilder.dialogs import DialogContext, DialogTurnResult +from botbuilder.dialogs.prompts import ( + NumberPrompt, + PromptOptions, + PromptValidatorContext, +) from botbuilder.core import ( MemoryStorage, ConversationState, @@ -10,14 +19,68 @@ ) from botbuilder.core.adapters import TestAdapter, TestFlow from botbuilder.dialogs import DialogSet, DialogTurnStatus +from botbuilder.schema import Activity, ActivityTypes + + +class NumberPromptMock(NumberPrompt): + def __init__( + self, + dialog_id: str, + validator: Callable[[PromptValidatorContext], bool] = None, + default_locale=None, + ): + super().__init__(dialog_id, validator, default_locale) + + async def on_prompt_null_context(self, options: PromptOptions): + # Should throw TypeError + await self.on_prompt( + turn_context=None, state=None, options=options, is_retry=False + ) + + async def on_prompt_null_options(self, dialog_context: DialogContext): + # Should throw TypeError + await self.on_prompt( + dialog_context.context, state=None, options=None, is_retry=False + ) + + async def on_recognize_null_context(self): + # Should throw TypeError + await self.on_recognize(turn_context=None, state=None, options=None) class NumberPromptTests(aiounittest.AsyncTestCase): - def test_empty_should_fail(self): + def test_empty_id_should_fail(self): # pylint: disable=no-value-for-parameter empty_id = "" self.assertRaises(TypeError, lambda: NumberPrompt(empty_id)) + def test_none_id_should_fail(self): + # pylint: disable=no-value-for-parameter + self.assertRaises(TypeError, lambda: NumberPrompt(dialog_id=None)) + + async def test_with_null_turn_context_should_fail(self): + number_prompt_mock = NumberPromptMock("NumberPromptMock") + + options = PromptOptions( + prompt=Activity(type=ActivityTypes.message, text="Please send a number.") + ) + + with self.assertRaises(TypeError): + await number_prompt_mock.on_prompt_null_context(options) + + async def test_on_prompt_with_null_options_fails(self): + conver_state = ConversationState(MemoryStorage()) + dialog_state = conver_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + number_prompt_mock = NumberPromptMock( + dialog_id="NumberPromptMock", validator=None, default_locale=Culture.English + ) + dialogs.add(number_prompt_mock) + + with self.assertRaises(TypeError): + await number_prompt_mock.on_recognize_null_context() + async def test_number_prompt(self): # Create new ConversationState with MemoryStorage and register the state as middleware. conver_state = ConversationState(MemoryStorage()) @@ -28,11 +91,10 @@ async def test_number_prompt(self): dialogs = DialogSet(dialog_state) # Create and add number prompt to DialogSet. - number_prompt = NumberPrompt("NumberPrompt", None, "English") + number_prompt = NumberPrompt("NumberPrompt", None, Culture.English) dialogs.add(number_prompt) async def exec_test(turn_context: TurnContext) -> None: - dialog_context = await dialogs.create_context(turn_context) results = await dialog_context.continue_dialog() @@ -62,3 +124,263 @@ async def exec_test(turn_context: TurnContext) -> None: test_flow3 = await test_flow2.assert_reply("Enter quantity of cable") test_flow4 = await test_flow3.send("Give me twenty meters of cable") await test_flow4.assert_reply("You asked me for '20' meters of cable.") + + # TODO: retry_prompt in NumberPrompt appears to be broken + # It when NumberPrompt fails to receive a number, it retries, prompting + # with the prompt and not retry prompt in options + async def test_number_prompt_retry(self): + async def exec_test(turn_context: TurnContext) -> None: + dialog_context: DialogContext = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity(type=ActivityTypes.message, text="Enter a number."), + retry_prompt=Activity( + type=ActivityTypes.message, text="You must enter a number." + ), + ) + await dialog_context.prompt("NumberPrompt", options) + elif results.status == DialogTurnStatus.Complete: + number_result = results.result + await turn_context.send_activity( + MessageFactory.text(f"Bot received the number '{number_result}'.") + ) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + number_prompt = NumberPrompt( + dialog_id="NumberPrompt", validator=None, default_locale=Culture.English + ) + dialogs.add(number_prompt) + + step1 = await adapter.send("hello") + await step1.assert_reply("Enter a number.") + # TODO: something is breaking in the validators or retry prompt + # where it does not accept the 2nd answer after reprompting the user + # for another value + # step3 = await step2.send("hello") + # step4 = await step3.assert_reply("You must enter a number.") + # step5 = await step4.send("64") + # await step5.assert_reply("Bot received the number '64'.") + + async def test_number_uses_locale_specified_in_constructor(self): + # Create new ConversationState with MemoryStorage and register the state as middleware. + conver_state = ConversationState(MemoryStorage()) + + # Create a DialogState property, DialogSet and register the WaterfallDialog. + dialog_state = conver_state.create_property("dialogState") + + dialogs = DialogSet(dialog_state) + + # Create and add number prompt to DialogSet. + number_prompt = NumberPrompt( + "NumberPrompt", None, default_locale=Culture.Spanish + ) + dialogs.add(number_prompt) + + async def exec_test(turn_context: TurnContext) -> None: + + dialog_context = await dialogs.create_context(turn_context) + results = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + await dialog_context.begin_dialog( + "NumberPrompt", + PromptOptions( + prompt=MessageFactory.text( + "How much money is in your gaming account?" + ) + ), + ) + else: + if results.status == DialogTurnStatus.Complete: + number_result = results.result + await turn_context.send_activity( + MessageFactory.text( + f"You say you have ${number_result} in your gaming account." + ) + ) + + await conver_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + test_flow = TestFlow(None, adapter) + + test_flow2 = await test_flow.send("Hello") + test_flow3 = await test_flow2.assert_reply( + "How much money is in your gaming account?" + ) + test_flow4 = await test_flow3.send("I've got $1.200.555,42 in my account.") + await test_flow4.assert_reply( + "You say you have $1200555.42 in your gaming account." + ) + + async def test_number_prompt_validator(self): + async def exec_test(turn_context: TurnContext) -> None: + dialog_context = await dialogs.create_context(turn_context) + results = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity(type=ActivityTypes.message, text="Enter a number."), + retry_prompt=Activity( + type=ActivityTypes.message, + text="You must enter a positive number less than 100.", + ), + ) + await dialog_context.prompt("NumberPrompt", options) + + elif results.status == DialogTurnStatus.Complete: + number_result = int(results.result) + await turn_context.send_activity( + MessageFactory.text(f"Bot received the number '{number_result}'.") + ) + + await conver_state.save_changes(turn_context) + + # Create new ConversationState with MemoryStorage and register the state as middleware. + conver_state = ConversationState(MemoryStorage()) + + # Create a DialogState property, DialogSet and register the WaterfallDialog. + dialog_state = conver_state.create_property("dialogState") + + dialogs = DialogSet(dialog_state) + + # Create and add number prompt to DialogSet. + async def validator(prompt_context: PromptValidatorContext): + result = prompt_context.recognized.value + + if 0 < result < 100: + return True + + return False + + number_prompt = NumberPrompt( + "NumberPrompt", validator, default_locale=Culture.English + ) + dialogs.add(number_prompt) + + adapter = TestAdapter(exec_test) + + step1 = await adapter.send("hello") + step2 = await step1.assert_reply("Enter a number.") + await step2.send("150") + # TODO: something is breaking in the validators or retry prompt + # where it does not accept the 2nd answer after reprompting the user + # for another value + # step4 = await step3.assert_reply("You must enter a positive number less than 100.") + # step5 = await step4.send("64") + # await step5.assert_reply("Bot received the number '64'.") + + async def test_float_number_prompt(self): + async def exec_test(turn_context: TurnContext) -> None: + dialog_context = await dialogs.create_context(turn_context) + results = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity(type=ActivityTypes.message, text="Enter a number.") + ) + await dialog_context.prompt("NumberPrompt", options) + + elif results.status == DialogTurnStatus.Complete: + number_result = float(results.result) + await turn_context.send_activity( + MessageFactory.text(f"Bot received the number '{number_result}'.") + ) + + await conver_state.save_changes(turn_context) + + # Create new ConversationState with MemoryStorage and register the state as middleware. + conver_state = ConversationState(MemoryStorage()) + + # Create a DialogState property, DialogSet and register the WaterfallDialog. + dialog_state = conver_state.create_property("dialogState") + + dialogs = DialogSet(dialog_state) + + # Create and add number prompt to DialogSet. + number_prompt = NumberPrompt( + "NumberPrompt", validator=None, default_locale=Culture.English + ) + dialogs.add(number_prompt) + + adapter = TestAdapter(exec_test) + + step1 = await adapter.send("hello") + step2 = await step1.assert_reply("Enter a number.") + step3 = await step2.send("3.14") + await step3.assert_reply("Bot received the number '3.14'.") + + async def test_number_prompt_uses_locale_specified_in_activity(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + results = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity(type=ActivityTypes.message, text="Enter a number.") + ) + await dialog_context.prompt("NumberPrompt", options) + + elif results.status == DialogTurnStatus.Complete: + number_result = float(results.result) + self.assertEqual(3.14, number_result) + + await conver_state.save_changes(turn_context) + + conver_state = ConversationState(MemoryStorage()) + dialog_state = conver_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + number_prompt = NumberPrompt("NumberPrompt", None, None) + dialogs.add(number_prompt) + + adapter = TestAdapter(exec_test) + + step1 = await adapter.send("hello") + step2 = await step1.assert_reply("Enter a number.") + await step2.send( + Activity(type=ActivityTypes.message, text="3,14", locale=Culture.Spanish) + ) + + async def test_number_prompt_defaults_to_en_us_culture(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + results = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity(type=ActivityTypes.message, text="Enter a number.") + ) + await dialog_context.prompt("NumberPrompt", options) + + elif results.status == DialogTurnStatus.Complete: + number_result = float(results.result) + await turn_context.send_activity( + MessageFactory.text(f"Bot received the number '{number_result}'.") + ) + + await conver_state.save_changes(turn_context) + + conver_state = ConversationState(MemoryStorage()) + dialog_state = conver_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + number_prompt = NumberPrompt("NumberPrompt") + dialogs.add(number_prompt) + + adapter = TestAdapter(exec_test) + + step1 = await adapter.send("hello") + step2 = await step1.assert_reply("Enter a number.") + step3 = await step2.send("3.14") + await step3.assert_reply("Bot received the number '3.14'.")
NumberPrompt Locale Not Fully Implemented ## Version v4.5 ## Describe the bug Found this bug while investigating for parity with regards to this [`NumberPrompt` bug filed in the dotnet repo](https://github.com/microsoft/botbuilder-dotnet/issues/2288) * in constructor, `default_locale` attribute is set, but never used in `NumberPrompt`'s implementation (not in `on_prompt()` nor `on_recognize()` * `on_recognize()` does allow you to pass in `locale` via `Activity`, however locale will not be used if only `default_locale` is specified * "`English`" is used as string to specify locale, when we should be using the constants provided by the python recognizers-text repo * Separately, there's definitely a lack of unit test coverage for this feature (only 2 tests written) ## Expected behavior * implement use of `default_locale` * implement use of recognizers-text constants to specify locale [bug]
Update: looks like python actually never parses the value from `str` to `float`/`int` in `NumberPrompt`, which deviates from the [behavior in dotnet repo](https://github.com/microsoft/botbuilder-dotnet/blob/master/libraries/Microsoft.Bot.Builder.Dialogs/Prompts/NumberPrompt.cs#L112). This bug should be fixed as well. Python: ```python results = recognize_number(message.text, culture) if results: result.succeeded = True result.value = results[0].resolution["value"] ``` ![image](https://user-images.githubusercontent.com/35248895/62323196-9832cb00-b45b-11e9-9a6f-cb007b54732c.png)
2019-08-01T20:42:00
microsoft/botbuilder-python
285
microsoft__botbuilder-python-285
[ "243" ]
9bdd0c4850cfadd24f21c57e332c281bdab22d09
diff --git a/libraries/botbuilder-core/botbuilder/core/activity_handler.py b/libraries/botbuilder-core/botbuilder/core/activity_handler.py --- a/libraries/botbuilder-core/botbuilder/core/activity_handler.py +++ b/libraries/botbuilder-core/botbuilder/core/activity_handler.py @@ -1,7 +1,8 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +from typing import List -from botbuilder.schema import ActivityTypes, ChannelAccount +from botbuilder.schema import ActivityTypes, ChannelAccount, MessageReaction from .turn_context import TurnContext @@ -27,6 +28,8 @@ async def on_turn(self, turn_context: TurnContext): await self.on_message_activity(turn_context) elif turn_context.activity.type == ActivityTypes.conversation_update: await self.on_conversation_update_activity(turn_context) + elif turn_context.activity.type == ActivityTypes.message_reaction: + await self.on_message_reaction_activity(turn_context) elif turn_context.activity.type == ActivityTypes.event: await self.on_event_activity(turn_context) else: @@ -64,6 +67,27 @@ async def on_members_removed_activity( ): # pylint: disable=unused-argument return + async def on_message_reaction_activity(self, turn_context: TurnContext): + if turn_context.activity.reactions_added is not None: + await self.on_reactions_added( + turn_context.activity.reactions_added, turn_context + ) + + if turn_context.activity.reactions_removed is not None: + await self.on_reactions_removed( + turn_context.activity.reactions_removed, turn_context + ) + + async def on_reactions_added( # pylint: disable=unused-argument + self, message_reactions: List[MessageReaction], turn_context: TurnContext + ): + return + + async def on_reactions_removed( # pylint: disable=unused-argument + self, message_reactions: List[MessageReaction], turn_context: TurnContext + ): + return + async def on_event_activity(self, turn_context: TurnContext): if turn_context.activity.name == "tokens/response": return await self.on_token_response_event(turn_context)
diff --git a/libraries/botbuilder-core/tests/test_activity_handler.py b/libraries/botbuilder-core/tests/test_activity_handler.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-core/tests/test_activity_handler.py @@ -0,0 +1,98 @@ +from typing import List + +import aiounittest +from botbuilder.core import ActivityHandler, BotAdapter, TurnContext +from botbuilder.schema import ( + Activity, + ActivityTypes, + ChannelAccount, + ConversationReference, + MessageReaction, +) + + +class TestingActivityHandler(ActivityHandler): + def __init__(self): + self.record: List[str] = [] + + async def on_message_activity(self, turn_context: TurnContext): + self.record.append("on_message_activity") + return await super().on_message_activity(turn_context) + + async def on_members_added_activity( + self, members_added: ChannelAccount, turn_context: TurnContext + ): + self.record.append("on_members_added_activity") + return await super().on_members_added_activity(members_added, turn_context) + + async def on_members_removed_activity( + self, members_removed: ChannelAccount, turn_context: TurnContext + ): + self.record.append("on_members_removed_activity") + return await super().on_members_removed_activity(members_removed, turn_context) + + async def on_message_reaction_activity(self, turn_context: TurnContext): + self.record.append("on_message_reaction_activity") + return await super().on_message_reaction_activity(turn_context) + + async def on_reactions_added( + self, message_reactions: List[MessageReaction], turn_context: TurnContext + ): + self.record.append("on_reactions_added") + return await super().on_reactions_added(message_reactions, turn_context) + + async def on_reactions_removed( + self, message_reactions: List[MessageReaction], turn_context: TurnContext + ): + self.record.append("on_reactions_removed") + return await super().on_reactions_removed(message_reactions, turn_context) + + async def on_token_response_event(self, turn_context: TurnContext): + self.record.append("on_token_response_event") + return await super().on_token_response_event(turn_context) + + async def on_event(self, turn_context: TurnContext): + self.record.append("on_event") + return await super().on_event(turn_context) + + async def on_unrecognized_activity_type(self, turn_context: TurnContext): + self.record.append("on_unrecognized_activity_type") + return await super().on_unrecognized_activity_type(turn_context) + + +class NotImplementedAdapter(BotAdapter): + async def delete_activity( + self, context: TurnContext, reference: ConversationReference + ): + raise NotImplementedError() + + async def send_activities(self, context: TurnContext, activities: List[Activity]): + raise NotImplementedError() + + async def update_activity(self, context: TurnContext, activity: Activity): + raise NotImplementedError() + + +class TestActivityHandler(aiounittest.AsyncTestCase): + async def test_message_reaction(self): + # Note the code supports multiple adds and removes in the same activity though + # a channel may decide to send separate activities for each. For example, Teams + # sends separate activities each with a single add and a single remove. + + # Arrange + activity = Activity( + type=ActivityTypes.message_reaction, + reactions_added=[MessageReaction(type="sad")], + reactions_removed=[MessageReaction(type="angry")], + ) + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 3 + assert bot.record[0] == "on_message_reaction_activity" + assert bot.record[1] == "on_reactions_added" + assert bot.record[2] == "on_reactions_removed"
Add support for Message Reactions to ActivityHandler ActivityHandler should be extended to include MessageReactions. This has now been added to the C# and The JavaScript. Here is a pointer to the JavaScript implementation: https://github.com/microsoft/botbuilder-js/pull/1038
2019-08-09T05:19:06
microsoft/botbuilder-python
287
microsoft__botbuilder-python-287
[ "286" ]
e449d439520ab2a64b22343b813e97304be0bcba
diff --git a/libraries/botbuilder-core/botbuilder/core/__init__.py b/libraries/botbuilder-core/botbuilder/core/__init__.py --- a/libraries/botbuilder-core/botbuilder/core/__init__.py +++ b/libraries/botbuilder-core/botbuilder/core/__init__.py @@ -25,6 +25,7 @@ from .null_telemetry_client import NullTelemetryClient from .recognizer import Recognizer from .recognizer_result import RecognizerResult, TopIntent +from .show_typing_middleware import ShowTypingMiddleware from .state_property_accessor import StatePropertyAccessor from .state_property_info import StatePropertyInfo from .storage import Storage, StoreItem, calculate_change_hash @@ -56,6 +57,7 @@ "NullTelemetryClient", "Recognizer", "RecognizerResult", + "ShowTypingMiddleware", "StatePropertyAccessor", "StatePropertyInfo", "Storage", diff --git a/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py b/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py @@ -0,0 +1,92 @@ +import time +from functools import wraps +from typing import Awaitable, Callable + +from botbuilder.schema import Activity, ActivityTypes + +from .middleware_set import Middleware +from .turn_context import TurnContext + + +def delay(span=0.0): + def wrap(func): + @wraps(func) + async def delayed(): + time.sleep(span) + await func() + + return delayed + + return wrap + + +class Timer: + clear_timer = False + + async def set_timeout(self, func, time): + is_invocation_cancelled = False + + @delay(time) + async def some_fn(): # pylint: disable=function-redefined + if not self.clear_timer: + await func() + + await some_fn() + return is_invocation_cancelled + + def set_clear_timer(self): + self.clear_timer = True + + +class ShowTypingMiddleware(Middleware): + def __init__(self, delay: float = 0.5, period: float = 2.0): + if delay < 0: + raise ValueError("Delay must be greater than or equal to zero") + + if period <= 0: + raise ValueError("Repeat period must be greater than zero") + + self._delay = delay + self._period = period + + async def on_process_request( + self, context: TurnContext, logic: Callable[[TurnContext], Awaitable] + ): + finished = False + timer = Timer() + + async def start_interval(context: TurnContext, delay: int, period: int): + async def aux(): + if not finished: + typing_activity = Activity( + type=ActivityTypes.typing, + relates_to=context.activity.relates_to, + ) + + conversation_reference = TurnContext.get_conversation_reference( + context.activity + ) + + typing_activity = TurnContext.apply_conversation_reference( + typing_activity, conversation_reference + ) + + await context.adapter.send_activities(context, [typing_activity]) + + start_interval(context, period, period) + + await timer.set_timeout(aux, delay) + + def stop_interval(): + nonlocal finished + finished = True + timer.set_clear_timer() + + if context.activity.type == ActivityTypes.message: + finished = False + await start_interval(context, self._delay, self._period) + + result = await logic() + stop_interval() + + return result
diff --git a/libraries/botbuilder-core/tests/test_show_typing_middleware.py b/libraries/botbuilder-core/tests/test_show_typing_middleware.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-core/tests/test_show_typing_middleware.py @@ -0,0 +1,65 @@ +import time +import aiounittest + +from botbuilder.core import ShowTypingMiddleware +from botbuilder.core.adapters import TestAdapter +from botbuilder.schema import ActivityTypes + + +class TestShowTypingMiddleware(aiounittest.AsyncTestCase): + async def test_should_automatically_send_a_typing_indicator(self): + async def aux(context): + time.sleep(0.600) + await context.send_activity(f"echo:{context.activity.text}") + + def assert_is_typing(activity, description): # pylint: disable=unused-argument + assert activity.type == ActivityTypes.typing + + adapter = TestAdapter(aux) + adapter.use(ShowTypingMiddleware()) + + step1 = await adapter.send("foo") + step2 = await step1.assert_reply(assert_is_typing) + step3 = await step2.assert_reply("echo:foo") + step4 = await step3.send("bar") + step5 = await step4.assert_reply(assert_is_typing) + await step5.assert_reply("echo:bar") + + async def test_should_not_automatically_send_a_typing_indicator_if_no_middleware( + self + ): + async def aux(context): + await context.send_activity(f"echo:{context.activity.text}") + + adapter = TestAdapter(aux) + + step1 = await adapter.send("foo") + await step1.assert_reply("echo:foo") + + async def test_should_not_immediately_respond_with_message(self): + async def aux(context): + time.sleep(0.600) + await context.send_activity(f"echo:{context.activity.text}") + + def assert_is_not_message( + activity, description + ): # pylint: disable=unused-argument + assert activity.type != ActivityTypes.message + + adapter = TestAdapter(aux) + adapter.use(ShowTypingMiddleware()) + + step1 = await adapter.send("foo") + await step1.assert_reply(assert_is_not_message) + + async def test_should_immediately_respond_with_message_if_no_middleware(self): + async def aux(context): + await context.send_activity(f"echo:{context.activity.text}") + + def assert_is_message(activity, description): # pylint: disable=unused-argument + assert activity.type == ActivityTypes.message + + adapter = TestAdapter(aux) + + step1 = await adapter.send("foo") + await step1.assert_reply(assert_is_message)
Implement ShowTypingMiddleware Implement ShowTypingMiddleware in botbuilder-core
2019-08-09T21:29:26
microsoft/botbuilder-python
290
microsoft__botbuilder-python-290
[ "145" ]
2d5b9d11e3c89decd96bf3a430023e67ea3c8a38
diff --git a/libraries/botbuilder-core/botbuilder/core/__init__.py b/libraries/botbuilder-core/botbuilder/core/__init__.py --- a/libraries/botbuilder-core/botbuilder/core/__init__.py +++ b/libraries/botbuilder-core/botbuilder/core/__init__.py @@ -23,6 +23,7 @@ from .message_factory import MessageFactory from .middleware_set import AnonymousReceiveMiddleware, Middleware, MiddlewareSet from .null_telemetry_client import NullTelemetryClient +from .private_conversation_state import PrivateConversationState from .recognizer import Recognizer from .recognizer_result import RecognizerResult, TopIntent from .show_typing_middleware import ShowTypingMiddleware @@ -55,6 +56,7 @@ "Middleware", "MiddlewareSet", "NullTelemetryClient", + "PrivateConversationState", "Recognizer", "RecognizerResult", "Severity", diff --git a/libraries/botbuilder-core/botbuilder/core/private_conversation_state.py b/libraries/botbuilder-core/botbuilder/core/private_conversation_state.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-core/botbuilder/core/private_conversation_state.py @@ -0,0 +1,36 @@ +from .bot_state import BotState +from .turn_context import TurnContext +from .storage import Storage + + +class PrivateConversationState(BotState): + def __init__(self, storage: Storage, namespace: str = ""): + async def aux_func(context: TurnContext) -> str: + nonlocal self + return await self.get_storage_key(context) + + self.namespace = namespace + super().__init__(storage, aux_func) + + def get_storage_key(self, turn_context: TurnContext) -> str: + activity = turn_context.activity + channel_id = activity.channel_id if activity is not None else None + + if not channel_id: + raise Exception("missing activity.channel_id") + + if activity and activity.conversation and activity.conversation.id is not None: + conversation_id = activity.conversation.id + else: + raise Exception("missing activity.conversation.id") + + if ( + activity + and activity.from_property + and activity.from_property.id is not None + ): + user_id = activity.from_property.id + else: + raise Exception("missing activity.from_property.id") + + return f"{channel_id}/conversations/{ conversation_id }/users/{ user_id }/{ self.namespace }"
diff --git a/libraries/botbuilder-core/tests/test_private_conversation_state.py b/libraries/botbuilder-core/tests/test_private_conversation_state.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-core/tests/test_private_conversation_state.py @@ -0,0 +1,36 @@ +import aiounittest + +from botbuilder.core import MemoryStorage, TurnContext, PrivateConversationState +from botbuilder.core.adapters import TestAdapter +from botbuilder.schema import Activity, ChannelAccount, ConversationAccount + +RECEIVED_MESSAGE = Activity( + text="received", + type="message", + channel_id="test", + conversation=ConversationAccount(id="convo"), + from_property=ChannelAccount(id="user"), +) + + +class TestPrivateConversationState(aiounittest.AsyncTestCase): + async def test_should_load_and_save_state_from_storage(self): + storage = MemoryStorage() + adapter = TestAdapter() + context = TurnContext(adapter, RECEIVED_MESSAGE) + private_conversation_state = PrivateConversationState(storage) + + # Simulate a "Turn" in a conversation by loading the state, + # changing it and then saving the changes to state. + await private_conversation_state.load(context) + key = private_conversation_state.get_storage_key(context) + state = private_conversation_state.get(context) + assert state == {}, "State not loaded" + assert key, "Key not found" + state["test"] = "foo" + await private_conversation_state.save_changes(context) + + # Check the storage to see if the changes to state were saved. + items = await storage.read([key]) + assert key in items, "Saved state not found in storage." + assert items[key]["test"] == "foo", "Missing test value in stored state."
PrivateConversationState Feature parity with https://github.com/Microsoft/botbuilder-dotnet
2019-08-09T22:28:50
microsoft/botbuilder-python
291
microsoft__botbuilder-python-291
[ "273" ]
8ce8c174a0b0294a49431df6f77318eb4e000829
diff --git a/libraries/botbuilder-core/botbuilder/core/turn_context.py b/libraries/botbuilder-core/botbuilder/core/turn_context.py --- a/libraries/botbuilder-core/botbuilder/core/turn_context.py +++ b/libraries/botbuilder-core/botbuilder/core/turn_context.py @@ -1,9 +1,10 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +import re from copy import copy from typing import List, Callable, Union, Dict -from botbuilder.schema import Activity, ConversationReference, ResourceResponse +from botbuilder.schema import Activity, ConversationReference, Mention, ResourceResponse class TurnContext: @@ -290,3 +291,44 @@ def apply_conversation_reference( activity.reply_to_id = reference.activity_id return activity + + @staticmethod + def get_reply_conversation_reference( + activity: Activity, reply: ResourceResponse + ) -> ConversationReference: + reference: ConversationReference = TurnContext.get_conversation_reference( + activity + ) + + # Update the reference with the new outgoing Activity's id. + reference.activity_id = reply.id + + return reference + + @staticmethod + def remove_recipient_mention(activity: Activity) -> str: + return TurnContext.remove_mention_text(activity, activity.recipient.id) + + @staticmethod + def remove_mention_text(activity: Activity, identifier: str) -> str: + mentions = TurnContext.get_mentions(activity) + for mention in mentions: + if mention.mentioned.id == identifier: + mention_name_match = re.match( + r"<at(.*)>(.*?)<\/at>", mention.text, re.IGNORECASE + ) + if mention_name_match: + activity.text = re.sub( + mention_name_match.groups()[1], "", activity.text + ) + activity.text = re.sub(r"<at><\/at>", "", activity.text) + return activity.text + + @staticmethod + def get_mentions(activity: Activity) -> List[Mention]: + result: List[Mention] = [] + if activity.entities is not None: + for entity in activity.entities: + if entity.type.lower() == "mention": + result.append(entity) + return result
diff --git a/libraries/botbuilder-core/tests/test_turn_context.py b/libraries/botbuilder-core/tests/test_turn_context.py --- a/libraries/botbuilder-core/tests/test_turn_context.py +++ b/libraries/botbuilder-core/tests/test_turn_context.py @@ -6,8 +6,9 @@ from botbuilder.schema import ( Activity, ChannelAccount, - ResourceResponse, ConversationAccount, + Mention, + ResourceResponse, ) from botbuilder.core import BotAdapter, TurnContext @@ -261,3 +262,39 @@ def test_apply_conversation_reference_when_is_incoming_is_true_should_not_prepar assert reply.conversation == ACTIVITY.conversation assert reply.service_url == ACTIVITY.service_url assert reply.channel_id == ACTIVITY.channel_id + + async def test_should_get_conversation_reference_using_get_reply_conversation_reference( + self + ): + context = TurnContext(SimpleAdapter(), ACTIVITY) + reply = await context.send_activity("test") + + assert reply.id, "reply has an id" + + reference = TurnContext.get_reply_conversation_reference( + context.activity, reply + ) + + assert reference.activity_id, "reference has an activity id" + assert ( + reference.activity_id == reply.id + ), "reference id matches outgoing reply id" + + def test_should_remove_at_mention_from_activity(self): + activity = Activity( + type="message", + text="<at>TestOAuth619</at> test activity", + recipient=ChannelAccount(id="TestOAuth619"), + entities=[ + Mention( + type="mention", + text="<at>TestOAuth619</at>", + mentioned=ChannelAccount(name="Bot", id="TestOAuth619"), + ) + ], + ) + + text = TurnContext.remove_recipient_mention(activity) + + assert text, " test activity" + assert activity.text, " test activity"
Remove Mention Support **Describe the solution you'd like** Add Remove Mention support as JS and C#. See ActivityExtensions for a reference of Mention related methods. To remove mentions from Activity.Text, see ActivityExtensions.RemoveMentionText and ActivityExtensions.RemoveRecipientMention. Note that in JS it is TurnContext.removeMentionText. **Describe alternatives you've considered** None **Additional context** I have implemented SkypeMentionNormalizeMiddleware on all platforms to correct Skype mentions. The user could still make use of this middleware, but would have to manually remove the mention from Activity.Text to have the same functionality as the other platforms. [enhancement]
2019-08-09T23:09:43
microsoft/botbuilder-python
295
microsoft__botbuilder-python-295
[ "144" ]
9632e440aad9734980c833cd98a62f921089766e
diff --git a/libraries/botbuilder-core/botbuilder/core/__init__.py b/libraries/botbuilder-core/botbuilder/core/__init__.py --- a/libraries/botbuilder-core/botbuilder/core/__init__.py +++ b/libraries/botbuilder-core/botbuilder/core/__init__.py @@ -20,6 +20,7 @@ from .intent_score import IntentScore from .invoke_response import InvokeResponse from .memory_storage import MemoryStorage +from .memory_transcript_store import MemoryTranscriptStore from .message_factory import MessageFactory from .middleware_set import AnonymousReceiveMiddleware, Middleware, MiddlewareSet from .null_telemetry_client import NullTelemetryClient @@ -55,6 +56,7 @@ "IntentScore", "InvokeResponse", "MemoryStorage", + "MemoryTranscriptStore", "MessageFactory", "Middleware", "MiddlewareSet", diff --git a/libraries/botbuilder-core/botbuilder/core/memory_transcript_store.py b/libraries/botbuilder-core/botbuilder/core/memory_transcript_store.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-core/botbuilder/core/memory_transcript_store.py @@ -0,0 +1,147 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +"""The memory transcript store stores transcripts in volatile memory.""" +import datetime +from typing import List, Dict +from botbuilder.schema import Activity +from .transcript_logger import PagedResult, TranscriptInfo, TranscriptStore + +# pylint: disable=line-too-long +class MemoryTranscriptStore(TranscriptStore): + """This provider is most useful for simulating production storage when running locally against the + emulator or as part of a unit test. + """ + + channels: Dict[str, Dict[str, Activity]] = {} + + async def log_activity(self, activity: Activity) -> None: + if not activity: + raise TypeError("activity cannot be None for log_activity()") + + # get channel + channel = {} + if not activity.channel_id in self.channels: + channel = {} + self.channels[activity.channel_id] = channel + else: + channel = self.channels[activity.channel_id] + + # Get conversation transcript. + transcript = [] + if activity.conversation.id in channel: + transcript = channel[activity.conversation.id] + else: + transcript = [] + channel[activity.conversation.id] = transcript + + transcript.append(activity) + + async def get_transcript_activities( + self, + channel_id: str, + conversation_id: str, + continuation_token: str = None, + start_date: datetime = datetime.datetime.min, + ) -> "PagedResult[Activity]": + if not channel_id: + raise TypeError("Missing channel_id") + + if not conversation_id: + raise TypeError("Missing conversation_id") + + paged_result = PagedResult() + if channel_id in self.channels: + channel = self.channels[channel_id] + if conversation_id in channel: + transcript = channel[conversation_id] + if continuation_token: + paged_result.items = ( + [ + x + for x in sorted( + transcript, key=lambda x: x.timestamp, reverse=False + ) + if x.timestamp >= start_date + ] + .dropwhile(lambda x: x.id != continuation_token) + .Skip(1)[:20] + ) + if paged_result.items.count == 20: + paged_result.continuation_token = paged_result.items[-1].id + else: + paged_result.items = [ + x + for x in sorted( + transcript, key=lambda x: x.timestamp, reverse=False + ) + if x.timestamp >= start_date + ][:20] + if paged_result.items.count == 20: + paged_result.continuation_token = paged_result.items[-1].id + + return paged_result + + async def delete_transcript(self, channel_id: str, conversation_id: str) -> None: + if not channel_id: + raise TypeError("channel_id should not be None") + + if not conversation_id: + raise TypeError("conversation_id should not be None") + + if channel_id in self.channels: + if conversation_id in self.channels[channel_id]: + del self.channels[channel_id][conversation_id] + + async def list_transcripts( + self, channel_id: str, continuation_token: str = None + ) -> "PagedResult[TranscriptInfo]": + if not channel_id: + raise TypeError("Missing channel_id") + + paged_result = PagedResult() + + if channel_id in self.channels: + channel: Dict[str, List[Activity]] = self.channels[channel_id] + + if continuation_token: + paged_result.items = ( + sorted( + [ + TranscriptInfo( + channel_id, + c.value()[0].timestamp if c.value() else None, + c.id, + ) + for c in channel + ], + key=lambda x: x.created, + reverse=True, + ) + .dropwhile(lambda x: x.id != continuation_token) + .Skip(1) + .Take(20) + ) + if paged_result.items.count == 20: + paged_result.continuation_token = paged_result.items[-1].id + else: + paged_result.items = ( + sorted( + [ + TranscriptInfo( + channel_id, + c.value()[0].timestamp if c.value() else None, + c.id, + ) + for c in channel + ], + key=lambda x: x.created, + reverse=True, + ) + .dropwhile(lambda x: x.id != continuation_token) + .Skip(1) + .Take(20) + ) + if paged_result.items.count == 20: + paged_result.continuation_token = paged_result.items[-1].id + + return paged_result diff --git a/libraries/botbuilder-core/botbuilder/core/transcript_logger.py b/libraries/botbuilder-core/botbuilder/core/transcript_logger.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-core/botbuilder/core/transcript_logger.py @@ -0,0 +1,197 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +"""Logs incoming and outgoing activities to a TranscriptStore..""" + +import datetime +import copy +from queue import Queue +from abc import ABC, abstractmethod +from typing import Awaitable, Callable, List +from botbuilder.schema import Activity, ActivityTypes, ConversationReference +from .middleware_set import Middleware +from .turn_context import TurnContext + + +class TranscriptLogger(ABC): + """Transcript logger stores activities for conversations for recall.""" + + @abstractmethod + async def log_activity(self, activity: Activity) -> None: + """Log an activity to the transcript. + :param activity:Activity being logged. + """ + raise NotImplementedError + + +class TranscriptLoggerMiddleware(Middleware): + """Logs incoming and outgoing activities to a TranscriptStore.""" + + def __init__(self, logger: TranscriptLogger): + if not logger: + raise TypeError( + "TranscriptLoggerMiddleware requires a TranscriptLogger instance." + ) + self.logger = logger + + async def on_process_request( + self, context: TurnContext, logic: Callable[[TurnContext], Awaitable] + ): + """Initialization for middleware. + :param context: Context for the current turn of conversation with the user. + :param logic: Function to call at the end of the middleware chain. + """ + transcript = Queue() + activity = context.activity + # Log incoming activity at beginning of turn + if activity: + if not activity.from_property.role: + activity.from_property.role = "user" + self.log_activity(transcript, copy.copy(activity)) + + # hook up onSend pipeline + # pylint: disable=unused-argument + async def send_activities_handler( + ctx: TurnContext, + activities: List[Activity], + next_send: Callable[[], Awaitable[None]], + ): + # Run full pipeline + responses = await next_send() + for activity in activities: + await self.log_activity(transcript, copy.copy(activity)) + return responses + + context.on_send_activities(send_activities_handler) + + # hook up update activity pipeline + async def update_activity_handler( + ctx: TurnContext, activity: Activity, next_update: Callable[[], Awaitable] + ): + # Run full pipeline + response = await next_update() + update_activity = copy.copy(activity) + update_activity.type = ActivityTypes.message_update + await self.log_activity(transcript, update_activity) + return response + + context.on_update_activity(update_activity_handler) + + # hook up delete activity pipeline + async def delete_activity_handler( + ctx: TurnContext, + reference: ConversationReference, + next_delete: Callable[[], Awaitable], + ): + # Run full pipeline + await next_delete() + + delete_msg = Activity( + type=ActivityTypes.message_delete, id=reference.activity_id + ) + deleted_activity: Activity = TurnContext.apply_conversation_reference( + delete_msg, reference, False + ) + await self.log_activity(transcript, deleted_activity) + + context.on_delete_activity(delete_activity_handler) + + if logic: + await logic() + + # Flush transcript at end of turn + while not transcript.empty(): + activity = transcript.get() + if activity is None: + break + await self.logger.log_activity(activity) + transcript.task_done() + + def log_activity(self, transcript: Queue, activity: Activity) -> None: + """Logs the activity. + :param transcript: transcript. + :param activity: Activity to log. + """ + transcript.put(activity) + + +class TranscriptStore(TranscriptLogger): + """ Transcript storage for conversations.""" + + @abstractmethod + async def get_transcript_activities( + self, + channel_id: str, + conversation_id: str, + continuation_token: str, + start_date: datetime, + ) -> "PagedResult": + """Get activities for a conversation (Aka the transcript). + :param channel_id: Channel Id where conversation took place. + :param conversation_id: Conversation ID + :param continuation_token: Continuation token to page through results. + :param start_date: Earliest time to include + :result: Page of results of Activity objects + """ + raise NotImplementedError + + @abstractmethod + async def list_transcripts( + self, channel_id: str, continuation_token: str + ) -> "PagedResult": + """List conversations in the channelId. + :param channel_id: Channel Id where conversation took place. + :param continuation_token : Continuation token to page through results. + :result: Page of results of TranscriptInfo objects + """ + raise NotImplementedError + + @abstractmethod + async def delete_transcript(self, channel_id: str, conversation_id: str) -> None: + """Delete a specific conversation and all of it's activities. + :param channel_id: Channel Id where conversation took place. + :param conversation_id: Id of the conversation to delete. + :result: None + """ + raise NotImplementedError + + +class ConsoleTranscriptLogger(TranscriptLogger): + """ConsoleTranscriptLogger writes activities to Console output.""" + + async def log_activity(self, activity: Activity) -> None: + """Log an activity to the transcript. + :param activity:Activity being logged. + """ + if activity: + print(f"Activity Log: {activity}") + else: + raise TypeError("Activity is required") + + +class TranscriptInfo: + """Metadata for a stored transcript.""" + + # pylint: disable=invalid-name + def __init__( + self, + channel_id: str = None, + created: datetime = None, + conversation_id: str = None, + ): + """ + :param channel_id: Channel ID the transcript was taken from + :param created: Timestamp when event created + :param id: Conversation ID + """ + self.channel_id = channel_id + self.created = created + self.id = conversation_id + + +class PagedResult: + """Paged results for transcript data.""" + + # Page of Items + items: List[object] = None + # Token used to page through multiple pages. + continuation_token: str = None
diff --git a/libraries/botbuilder-core/tests/test_memory_transcript_store.py b/libraries/botbuilder-core/tests/test_memory_transcript_store.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-core/tests/test_memory_transcript_store.py @@ -0,0 +1,124 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +# pylint: disable=missing-docstring, unused-import +import sys +import copy +import uuid +import datetime +from typing import Awaitable, Callable, Dict, List +from unittest.mock import patch, Mock +import aiounittest + +from botbuilder.core import ( + AnonymousReceiveMiddleware, + BotTelemetryClient, + MemoryTranscriptStore, + MiddlewareSet, + Middleware, + TurnContext, +) +from botbuilder.core.adapters import TestAdapter, TestFlow +from botbuilder.schema import ( + Activity, + ActivityTypes, + ChannelAccount, + ConversationAccount, + ConversationReference, +) + +# pylint: disable=line-too-long,missing-docstring +class TestMemoryTranscriptStore(aiounittest.AsyncTestCase): + # pylint: disable=unused-argument + async def test_null_transcript_store(self): + memory_transcript = MemoryTranscriptStore() + with self.assertRaises(TypeError): + await memory_transcript.log_activity(None) + + async def test_log_activity(self): + memory_transcript = MemoryTranscriptStore() + conversation_id = "_log_activity" + date = datetime.datetime.now() + activity = self.create_activities(conversation_id, date, 1)[-1] + await memory_transcript.log_activity(activity) + + async def test_get_activity_none(self): + memory_transcript = MemoryTranscriptStore() + conversation_id = "_log_activity" + await memory_transcript.get_transcript_activities("test", conversation_id) + + async def test_get_single_activity(self): + memory_transcript = MemoryTranscriptStore() + conversation_id = "_log_activity" + date = datetime.datetime.now() + activity = self.create_activities(conversation_id, date, count=1)[-1] + await memory_transcript.log_activity(activity) + result = await memory_transcript.get_transcript_activities( + "test", conversation_id + ) + self.assertNotEqual(result.items, None) + self.assertEqual(result.items[0].text, "0") + + async def test_get_multiple_activity(self): + memory_transcript = MemoryTranscriptStore() + conversation_id = "_log_activity" + date = datetime.datetime.now() + activities = self.create_activities(conversation_id, date, count=10) + for activity in activities: + await memory_transcript.log_activity(activity) + result = await memory_transcript.get_transcript_activities( + "test", conversation_id + ) + self.assertNotEqual(result.items, None) + self.assertEqual(len(result.items), 20) # 2 events logged each iteration + + async def test_delete_transcript(self): + memory_transcript = MemoryTranscriptStore() + conversation_id = "_log_activity" + date = datetime.datetime.now() + activity = self.create_activities(conversation_id, date, count=1)[-1] + await memory_transcript.log_activity(activity) + result = await memory_transcript.get_transcript_activities( + "test", conversation_id + ) + self.assertNotEqual(result.items, None) + await memory_transcript.delete_transcript("test", conversation_id) + result = await memory_transcript.get_transcript_activities( + "test", conversation_id + ) + self.assertEqual(result.items, None) + + def create_activities(self, conversation_id: str, date: datetime, count: int = 5): + activities: List[Activity] = [] + time_stamp = date + for i in range(count): + activities.append( + Activity( + type=ActivityTypes.message, + timestamp=time_stamp, + id=str(uuid.uuid4()), + text=str(i), + channel_id="test", + from_property=ChannelAccount(id=f"User{i}"), + conversation=ConversationAccount(id=conversation_id), + recipient=ChannelAccount(id="bot1", name="2"), + service_url="http://foo.com/api/messages", + ) + ) + time_stamp = time_stamp + datetime.timedelta(0, 60) + activities.append( + Activity( + type=ActivityTypes.message, + timestamp=date, + id=str(uuid.uuid4()), + text=str(i), + channel_id="test", + from_property=ChannelAccount(id="Bot1", name="2"), + conversation=ConversationAccount(id=conversation_id), + recipient=ChannelAccount(id=f"User{i}"), + service_url="http://foo.com/api/messages", + ) + ) + time_stamp = time_stamp + datetime.timedelta( + 0, 60 + ) # days, seconds, then other fields. + return activities diff --git a/libraries/botbuilder-core/tests/test_private_conversation_state.py b/libraries/botbuilder-core/tests/test_private_conversation_state.py --- a/libraries/botbuilder-core/tests/test_private_conversation_state.py +++ b/libraries/botbuilder-core/tests/test_private_conversation_state.py @@ -1,3 +1,6 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + import aiounittest from botbuilder.core import MemoryStorage, TurnContext, PrivateConversationState diff --git a/libraries/botbuilder-core/tests/test_show_typing_middleware.py b/libraries/botbuilder-core/tests/test_show_typing_middleware.py --- a/libraries/botbuilder-core/tests/test_show_typing_middleware.py +++ b/libraries/botbuilder-core/tests/test_show_typing_middleware.py @@ -1,3 +1,6 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + import time import aiounittest
Transcript logger Feature parity with https://github.com/Microsoft/botbuilder-dotnet
2019-08-12T21:43:51
microsoft/botbuilder-python
296
microsoft__botbuilder-python-296
[ "225" ]
f9e26b5f78401cbdd4d1e345db2a755f63bcafda
diff --git a/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py b/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py --- a/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py +++ b/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py @@ -763,6 +763,8 @@ class ConversationAccount(Model): :type role: str or ~botframework.connector.models.RoleTypes :param tenant_id: This conversation's tenant ID :type tenant_id: str + :param properties: This conversation's properties + :type properties: object """ _attribute_map = { @@ -773,6 +775,7 @@ class ConversationAccount(Model): "aad_object_id": {"key": "aadObjectId", "type": "str"}, "role": {"key": "role", "type": "str"}, "tenant_id": {"key": "tenantID", "type": "str"}, + "properties": {"key": "properties", "type": "object"}, } def __init__( @@ -785,6 +788,7 @@ def __init__( aad_object_id: str = None, role=None, tenant_id=None, + properties=None, **kwargs ) -> None: super(ConversationAccount, self).__init__(**kwargs) @@ -795,6 +799,7 @@ def __init__( self.aad_object_id = aad_object_id self.role = role self.tenant_id = tenant_id + self.properties = properties class ConversationMembers(Model):
Add 'properties' property to conversationAccount See https://github.com/microsoft/botbuilder-js/pull/999 **Additional context** This is not in the swagger file, but exists in both dotnet and javascript. This should exist in Python as well. [enhancement]
2019-08-13T17:03:55
microsoft/botbuilder-python
299
microsoft__botbuilder-python-299
[ "292" ]
c98eb965812bb7cc73a33c76af1132a26678af27
diff --git a/samples/13.core-bot/dialogs/date_resolver_dialog.py b/samples/13.core-bot/dialogs/date_resolver_dialog.py --- a/samples/13.core-bot/dialogs/date_resolver_dialog.py +++ b/samples/13.core-bot/dialogs/date_resolver_dialog.py @@ -56,7 +56,7 @@ async def initial_step( PromptOptions(prompt=prompt_msg, retry_prompt=reprompt_msg), ) # We have a Date we just need to check it is unambiguous. - if "definite" in Timex(timex).types: + if "definite" not in Timex(timex).types: # This is essentially a "reprompt" of the data we were given up front. return await step_context.prompt( DateTimePrompt.__name__, PromptOptions(prompt=reprompt_msg) diff --git a/samples/13.core-bot/dialogs/main_dialog.py b/samples/13.core-bot/dialogs/main_dialog.py --- a/samples/13.core-bot/dialogs/main_dialog.py +++ b/samples/13.core-bot/dialogs/main_dialog.py @@ -1,17 +1,13 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from datetime import datetime -from typing import Dict from botbuilder.dialogs import ( ComponentDialog, - DialogSet, - DialogTurnStatus, WaterfallDialog, WaterfallStepContext, DialogTurnResult, ) -from botbuilder.dialogs.prompts import TextPrompt, ConfirmPrompt, PromptOptions +from botbuilder.dialogs.prompts import TextPrompt, PromptOptions from botbuilder.core import MessageFactory, TurnContext from botbuilder.schema import InputHints @@ -76,9 +72,8 @@ async def act_step(self, step_context: WaterfallStepContext) -> DialogTurnResult self._luis_recognizer, step_context.context ) - # top_intent = cognitive_models_helper.top_intent(luis_result['intents']) - if intent == Intent.BOOK_FLIGHT.value and luis_result: + # Show a warning for Origin and Destination if we can't resolve them. await MainDialog._show_warning_for_unsupported_cities( step_context.context, luis_result ) diff --git a/samples/13.core-bot/helpers/luis_helper.py b/samples/13.core-bot/helpers/luis_helper.py --- a/samples/13.core-bot/helpers/luis_helper.py +++ b/samples/13.core-bot/helpers/luis_helper.py @@ -2,7 +2,7 @@ # Licensed under the MIT License. from enum import Enum from typing import Dict -from botbuilder.ai.luis import LuisRecognizer, LuisApplication +from botbuilder.ai.luis import LuisRecognizer from botbuilder.core import IntentScore, TopIntent, TurnContext from booking_details import BookingDetails @@ -32,6 +32,9 @@ class LuisHelper: async def execute_luis_query( luis_recognizer: LuisRecognizer, turn_context: TurnContext ) -> (Intent, object): + """ + Returns an object with preformatted LUIS results for the bot's dialogs to consume. + """ result = None intent = None @@ -78,13 +81,20 @@ async def execute_luis_query( from_entities[0]["text"].capitalize() ) - # TODO: This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part. + # This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop the Time part. # TIMEX is a format that represents DateTime expressions that include some ambiguity. e.g. missing a Year. - date_entities = recognizer_result.entities.get("$instance", {}).get( - "datetime", [] - ) - if len(date_entities) > 0: - result.travel_date = None # TODO: Set when we get a timex format + date_entities = recognizer_result.entities.get("datetime", []) + if date_entities: + timex = date_entities[0]["timex"] + + if timex: + datetime = timex[0].split("T")[0] + + result.travel_date = datetime + + else: + result.travel_date = None + except Exception as e: print(e)
date_resolver_dialog - test of "definite" ## Version SDK v4.5.0b3 in botbuilder-python/samples/13.core-bot/dialogs/date_resolver_dialog.py ## Describe the bug Line : _if "definite" in Timex(timex).types:_ The goal of this line is to treat ambiguous date such as timex date = XXXX-05-17 so the test must be "not in" instead of "in" ("definite" = type for an unambiguous date) [bug]
Hmm, it looks like the behavior in the Python version of CoreBot is different from the behavior of what happens in C# and JS versions. I'll need to investigate further on why the discrepancy occurs though ___ For the line that you pointed out in question, for it the bot actually ventures down the if statement checking for for definite inside date resolver dialog if you: * start the dialog with an ambiguous date * answer with the "to" and "from" locations in the next prompts asking for flight cities * it should then detect that the initial date was given in the first utterance, and that that utterance is ambiguous, and send that "reprompt" given in date resolver dialog ### Example of Behavior in JS/C# ![image](https://user-images.githubusercontent.com/35248895/62894201-254e0d80-bd01-11e9-9843-5c531aafd027.png) ### Example of Behavior in Python ![image](https://user-images.githubusercontent.com/35248895/62894299-52022500-bd01-11e9-933f-543861a55777.png) Notice above it doesn't seem to detect that a date was initially given, nor does it reprompt, _even when changing the if statement you pointed out to use `not in`_ I tried changing where the `not` was placed "just in case" it made a difference, but it doesn't. ![image](https://user-images.githubusercontent.com/35248895/62894498-a3aaaf80-bd01-11e9-8625-9ee499695ec0.png) Running in debugger mode, I myself can't seem to get it to hit that if statement--seems to end that dialog before it would even reach it maybe? Investigating further... Ah ok, looks like it never hits LN 59 `if "definite" not in Timex(timex).types` in `date_resolver_dialog.py`, because the `step_context.options` is `None`, and therefore always will hit LN 52 `if timex is None` prompt and never gets to LN 59. I'll dig to see why this is, so we can finally hit LN 59 and ensure the changes produce the behavior expected Ok, dug down and figured out why the sample bot is breaking on entities. `MainDialog` calls `LuisHelper.execute_luis_query` to get `intent` and `result` * If you take a look at `luis_helper.py`, you can see that the `execute_luis_query` method does indeed return `intent` & `result`. * Separately, we have the raw LUIS result that came from calling LUIS endpoint to predict intent, saved in `recognizer_result`. * The issue is **we never save any of the parsed entity values specifically for datetime from `recognizer_result` to `result` that gets returned, so therefore all the datetime travel_date value in `result` that `MainDialog` has is`None`** Fixing the above issue first, then can actually hit the `if "definite" not in Timex(timex).type` statement originally reported.
2019-08-14T19:23:36
microsoft/botbuilder-python
302
microsoft__botbuilder-python-302
[ "281" ]
dcc99c20aae310f41b15bf164e52b3c06c688e1b
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/number_prompt.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/number_prompt.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/number_prompt.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/number_prompt.py @@ -40,7 +40,7 @@ async def on_prompt( raise TypeError("NumberPrompt.on_prompt(): options cannot be None.") if is_retry and options.retry_prompt is not None: - turn_context.send_activity(options.retry_prompt) + await turn_context.send_activity(options.retry_prompt) elif options.prompt is not None: await turn_context.send_activity(options.prompt)
diff --git a/libraries/botbuilder-dialogs/tests/test_number_prompt.py b/libraries/botbuilder-dialogs/tests/test_number_prompt.py --- a/libraries/botbuilder-dialogs/tests/test_number_prompt.py +++ b/libraries/botbuilder-dialogs/tests/test_number_prompt.py @@ -125,9 +125,6 @@ async def exec_test(turn_context: TurnContext) -> None: test_flow4 = await test_flow3.send("Give me twenty meters of cable") await test_flow4.assert_reply("You asked me for '20' meters of cable.") - # TODO: retry_prompt in NumberPrompt appears to be broken - # It when NumberPrompt fails to receive a number, it retries, prompting - # with the prompt and not retry prompt in options async def test_number_prompt_retry(self): async def exec_test(turn_context: TurnContext) -> None: dialog_context: DialogContext = await dialogs.create_context(turn_context) @@ -161,14 +158,11 @@ async def exec_test(turn_context: TurnContext) -> None: dialogs.add(number_prompt) step1 = await adapter.send("hello") - await step1.assert_reply("Enter a number.") - # TODO: something is breaking in the validators or retry prompt - # where it does not accept the 2nd answer after reprompting the user - # for another value - # step3 = await step2.send("hello") - # step4 = await step3.assert_reply("You must enter a number.") - # step5 = await step4.send("64") - # await step5.assert_reply("Bot received the number '64'.") + step2 = await step1.assert_reply("Enter a number.") + step3 = await step2.send("hello") + step4 = await step3.assert_reply("You must enter a number.") + step5 = await step4.send("64") + await step5.assert_reply("Bot received the number '64'.") async def test_number_uses_locale_specified_in_constructor(self): # Create new ConversationState with MemoryStorage and register the state as middleware. @@ -272,13 +266,12 @@ async def validator(prompt_context: PromptValidatorContext): step1 = await adapter.send("hello") step2 = await step1.assert_reply("Enter a number.") - await step2.send("150") - # TODO: something is breaking in the validators or retry prompt - # where it does not accept the 2nd answer after reprompting the user - # for another value - # step4 = await step3.assert_reply("You must enter a positive number less than 100.") - # step5 = await step4.send("64") - # await step5.assert_reply("Bot received the number '64'.") + step3 = await step2.send("150") + step4 = await step3.assert_reply( + "You must enter a positive number less than 100." + ) + step5 = await step4.send("64") + await step5.assert_reply("Bot received the number '64'.") async def test_float_number_prompt(self): async def exec_test(turn_context: TurnContext) -> None:
NumberPrompt doesn't accept retry value ## Version v4.5 ## Describe the bug When you send an invalid number to a `NumberPrompt`, it sends out a retry prompt. When attempting to send a 2nd response after being reprompted, you get a timeout error. ## To Reproduce 1. Create a `NumberPrompt` object 2. When it prompts you for a number, send in a non-numeric value (e.g. `"hello"`) * this will trigger a retry prompt (e.g. `"You must enter a number."`) 3. Try sending in another value--no matter what type of value, you get a timeout error ![image](https://user-images.githubusercontent.com/35248895/62598200-7000fd00-b89d-11e9-9b02-cc04beb609d4.png) ![image](https://user-images.githubusercontent.com/35248895/62598223-8444fa00-b89d-11e9-918b-8578efd179ac.png) ## Expected behavior To be able to send in a 2nd value when reprompted ## Additional context ```python async def test_number_prompt_retry(self): async def exec_test(turn_context: TurnContext) -> None: dialog_context: DialogContext = await dialogs.create_context(turn_context) results: DialogTurnResult = await dialog_context.continue_dialog() if results.status == DialogTurnStatus.Empty: options = PromptOptions( prompt=Activity(type=ActivityTypes.message, text="Enter a number."), retry_prompt=Activity( type=ActivityTypes.message, text="You must enter a number." ), ) await dialog_context.prompt("NumberPrompt", options) elif results.status == DialogTurnStatus.Complete: number_result = results.result await turn_context.send_activity( MessageFactory.text(f"Bot received the number '{number_result}'.") ) await convo_state.save_changes(turn_context) adapter = TestAdapter(exec_test) convo_state = ConversationState(MemoryStorage()) dialog_state = convo_state.create_property("dialogState") dialogs = DialogSet(dialog_state) number_prompt = NumberPrompt( dialog_id="NumberPrompt", validator=None, default_locale=Culture.English ) dialogs.add(number_prompt) step1 = await adapter.send("hello") step2 = await step1.assert_reply("Enter a number.") # TODO: something is breaking in the validators or retry prompt # where it does not accept the 2nd answer after reprompting the user # for another value step3 = await step2.send("hello") step4 = await step3.assert_reply("You must enter a number.") step5 = await step4.send("64") await step5.assert_reply("Bot received the number '64'.") ``` [bug]
2019-08-15T21:27:52
microsoft/botbuilder-python
307
microsoft__botbuilder-python-307
[ "306" ]
31dd7acde8b72c8f961d75532d61cd255466a96b
diff --git a/samples/45.state-management/bots/state_management_bot.py b/samples/45.state-management/bots/state_management_bot.py --- a/samples/45.state-management/bots/state_management_bot.py +++ b/samples/45.state-management/bots/state_management_bot.py @@ -59,7 +59,9 @@ async def on_message_activity(self, turn_context: TurnContext): user_profile.name = turn_context.activity.text # Acknowledge that we got their name. - await turn_context.send_activity(f"Thanks { user_profile.name }.") + await turn_context.send_activity( + f"Thanks { user_profile.name }. To see conversation data, type anything." + ) # Reset the flag to allow the bot to go though the cycle again. conversation_data.prompted_for_user_name = False
Minor differences in what's displayed after user response 45.state-management bot ## Version v4.50b4 ## Describe the bug There's a minor difference in what's displayed after the user responds to the bot. The javascript_nodejs bot exhibits the same behavior (see [issue 1718](https://github.com/microsoft/BotBuilder-Samples/issues/1718) for more information). ## To Reproduce Run bot per README.md instructions 1. go to bot's folder 2. run `python install -r requirement.txt`, then run `python app.py` 3. open in Emulator The csharp_dotnet and javascript_nodejs bots were also run via CLI. ## Expected behavior Bot should look and function just like bots in other languages (specifically csharp_dotnet bot since there are currently issues with javascript_nodejs sample). ## Screenshots **charp_dotnetcore bot**: Bot responds with, "Thanks <string_user_responded_with. To see conversation data, type anything." after user's second response. Also welcomes users. This is IMHO the best version/gold standard for the sample currently. ![45-csharp](https://user-images.githubusercontent.com/9682548/63467941-73f35a00-c41b-11e9-901f-9151a894317f.png) **Python bot**: Bot responds with, "Thanks <string_user_responded_with." after user's second response. Also welcomes user. ![45-python](https://user-images.githubusercontent.com/9682548/63467950-78b80e00-c41b-11e9-9e2c-a6651e3247ec.png) **javascript_nodejs bot**: Bot responds with, "Thanks <string_user_responded_with." after user's second response. Does not welcome user (addressed in [issue 1718](https://github.com/microsoft/BotBuilder-Samples/issues/1718)). ![45 -javascript](https://user-images.githubusercontent.com/9682548/63467957-7d7cc200-c41b-11e9-9c11-f5495d3bfa25.png) ## Additional context To fix: Add **"To see conversation data, type anything."** to the string in **line 62** in 45.state-management/bots/state_management_bot.py
2019-08-22T12:32:01
microsoft/botbuilder-python
324
microsoft__botbuilder-python-324
[ "315" ]
bb0b7ef3050698ed48e979c23cdaee8060add2a6
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_factory.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_factory.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_factory.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_factory.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import List +from typing import List, Union from botbuilder.core import CardFactory, MessageFactory from botbuilder.schema import ActionTypes, Activity, CardAction, HeroCard, InputHints @@ -17,7 +17,7 @@ class ChoiceFactory: @staticmethod def for_channel( channel_id: str, - choices: List[Choice], + choices: List[Union[str, Choice]], text: str = None, speak: str = None, options: ChoiceFactoryOptions = None, @@ -36,8 +36,7 @@ def for_channel( if channel_id is None: channel_id = "" - if choices is None: - choices = [] + choices = ChoiceFactory._to_choices(choices) # Find maximum title length max_title_length = 0 @@ -74,7 +73,7 @@ def for_channel( @staticmethod def inline( - choices: List[Choice], + choices: List[Union[str, Choice]], text: str = None, speak: str = None, options: ChoiceFactoryOptions = None, @@ -89,8 +88,7 @@ def inline( speak: (Optional) SSML. Text to be spoken by your bot on a speech-enabled channel. options: (Optional) The formatting options to use to tweak rendering of list. """ - if choices is None: - choices = [] + choices = ChoiceFactory._to_choices(choices) if options is None: options = ChoiceFactoryOptions() @@ -134,7 +132,7 @@ def inline( @staticmethod def list_style( - choices: List[Choice], + choices: List[Union[str, Choice]], text: str = None, speak: str = None, options: ChoiceFactoryOptions = None, @@ -153,8 +151,7 @@ def list_style( options: (Optional) The formatting options to use to tweak rendering of list. """ - if choices is None: - choices = [] + choices = ChoiceFactory._to_choices(choices) if options is None: options = ChoiceFactoryOptions() @@ -206,7 +203,7 @@ def suggested_action( @staticmethod def hero_card( - choices: List[Choice], text: str = None, speak: str = None + choices: List[Union[Choice, str]], text: str = None, speak: str = None ) -> Activity: """ Creates a message activity that includes a lsit of coices that have been added as `HeroCard`'s @@ -221,18 +218,22 @@ def hero_card( ) @staticmethod - def _to_choices(choices: List[str]) -> List[Choice]: + def _to_choices(choices: List[Union[str, Choice]]) -> List[Choice]: """ Takes a list of strings and returns them as [`Choice`]. """ if choices is None: return [] - return [Choice(value=choice.value) for choice in choices] + return [ + Choice(value=choice) if isinstance(choice, str) else choice + for choice in choices + ] @staticmethod - def _extract_actions(choices: List[Choice]) -> List[CardAction]: + def _extract_actions(choices: List[Union[str, Choice]]) -> List[CardAction]: if choices is None: choices = [] + choices = ChoiceFactory._to_choices(choices) card_actions: List[CardAction] = [] for choice in choices: if choice.action is not None: diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt.py @@ -217,8 +217,11 @@ def default() -> Activity: ): prompt.suggested_actions = msg.suggested_actions - if msg.attachments is not None and msg.attachments: - prompt.attachments = msg.attachments + if msg.attachments: + if prompt.attachments: + prompt.attachments.extend(msg.attachments) + else: + prompt.attachments = msg.attachments return prompt
diff --git a/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py b/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py --- a/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py +++ b/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py @@ -352,7 +352,7 @@ async def assert_reply( :param timeout: :return: """ - + # TODO: refactor method so expected can take a Callable[[Activity], None] def default_inspector(reply, description=None): if isinstance(expected, Activity): validate_activity(reply, expected) diff --git a/libraries/botbuilder-dialogs/tests/test_choice_prompt.py b/libraries/botbuilder-dialogs/tests/test_choice_prompt.py --- a/libraries/botbuilder-dialogs/tests/test_choice_prompt.py +++ b/libraries/botbuilder-dialogs/tests/test_choice_prompt.py @@ -6,7 +6,7 @@ import aiounittest from recognizers_text import Culture -from botbuilder.core import ConversationState, MemoryStorage, TurnContext +from botbuilder.core import CardFactory, ConversationState, MemoryStorage, TurnContext from botbuilder.core.adapters import TestAdapter from botbuilder.dialogs import DialogSet, DialogTurnResult, DialogTurnStatus from botbuilder.dialogs.choices import Choice, ListStyle @@ -588,3 +588,108 @@ async def exec_test(turn_context: TurnContext): ) step3 = await step2.send("1") await step3.assert_reply("red") + + async def test_should_display_choices_on_hero_card(self): + size_choices = ["large", "medium", "small"] + + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a size." + ), + choices=size_choices, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + def assert_expected_activity( + activity: Activity, description + ): # pylint: disable=unused-argument + assert len(activity.attachments) == 1 + assert ( + activity.attachments[0].content_type + == CardFactory.content_types.hero_card + ) + assert activity.attachments[0].content.text == "Please choose a size." + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + choice_prompt = ChoicePrompt("prompt") + + # Change the ListStyle of the prompt to ListStyle.none. + choice_prompt.style = ListStyle.hero_card + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply(assert_expected_activity) + step3 = await step2.send("1") + await step3.assert_reply(size_choices[0]) + + async def test_should_display_choices_on_hero_card_with_additional_attachment(self): + size_choices = ["large", "medium", "small"] + card = CardFactory.adaptive_card( + { + "type": "AdaptiveCard", + "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", + "version": "1.2", + "body": [], + } + ) + card_activity = Activity(attachments=[card]) + + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions(prompt=card_activity, choices=size_choices) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + def assert_expected_activity( + activity: Activity, description + ): # pylint: disable=unused-argument + assert len(activity.attachments) == 2 + assert ( + activity.attachments[0].content_type + == CardFactory.content_types.adaptive_card + ) + assert ( + activity.attachments[1].content_type + == CardFactory.content_types.hero_card + ) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + choice_prompt = ChoicePrompt("prompt") + + # Change the ListStyle of the prompt to ListStyle.none. + choice_prompt.style = ListStyle.hero_card + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + await step1.assert_reply(assert_expected_activity)
Concat Attachments if exist in Prompt::AppendChoices ## Describe the bug Attachments from Prompt message should combine with Attachments from Choice (if they are both present). ## To Reproduce Steps to reproduce the behavior: 1. Create a ChoicePrompt with a Prompt message containing an attachment and some choices 2. set PromptOptions.Style to ListStyle.HeroCard 3. Message the bot 4. Notice the attachment on the Prompt message is not shown Code: https://github.com/microsoft/botbuilder-python/blob/master/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt.py#L221 ## Expected behavior Prompt message attachment should be combined with Choice Attachment (if both are present) ## Additional context Parity with cs: https://github.com/microsoft/botbuilder-dotnet/pull/2520 [bug]
2019-09-27T22:58:03
microsoft/botbuilder-python
326
microsoft__botbuilder-python-326
[ "254" ]
290af73f06e64a1a08810e44bd7362c29d937e59
diff --git a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py --- a/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py +++ b/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py @@ -8,7 +8,13 @@ from azure.cognitiveservices.language.luis.runtime.models import LuisResult from msrest.authentication import CognitiveServicesCredentials -from botbuilder.core import BotAssert, IntentScore, RecognizerResult, TurnContext +from botbuilder.core import ( + BotAssert, + IntentScore, + Recognizer, + RecognizerResult, + TurnContext, +) from botbuilder.schema import ActivityTypes from . import LuisApplication, LuisPredictionOptions, LuisTelemetryConstants @@ -16,7 +22,7 @@ from .luis_util import LuisUtil -class LuisRecognizer: +class LuisRecognizer(Recognizer): """ A LUIS based implementation of <see cref="IRecognizer"/>. """ @@ -95,7 +101,7 @@ def top_intent( return top_intent or default_intent - async def recognize( + async def recognize( # pylint: disable=arguments-differ self, turn_context: TurnContext, telemetry_properties: Dict[str, str] = None, diff --git a/libraries/botbuilder-core/botbuilder/core/recognizer.py b/libraries/botbuilder-core/botbuilder/core/recognizer.py --- a/libraries/botbuilder-core/botbuilder/core/recognizer.py +++ b/libraries/botbuilder-core/botbuilder/core/recognizer.py @@ -1,12 +1,12 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from abc import ABC +from abc import ABC, abstractmethod from .turn_context import TurnContext from .recognizer_result import RecognizerResult class Recognizer(ABC): - @staticmethod - async def recognize(turn_context: TurnContext) -> RecognizerResult: + @abstractmethod + async def recognize(self, turn_context: TurnContext) -> RecognizerResult: raise NotImplementedError()
LuisRecognizer is missing use of interface ## Version What package version of the SDK are you using. ## Describe the bug Give a clear and concise description of what the bug is. ## To Reproduce Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error ## Expected behavior Give a clear and concise description of what you expected to happen. ## Screenshots If applicable, add screenshots to help explain your problem. ## Additional context Add any other context about the problem here. [bug]
Created PR #255 as a fix for this. Can move interface to where ever preferred if there is any feedback. This item is of particular need when trying to build out a bot that can be tested with a Mock Recognizer
2019-09-30T17:50:44
microsoft/botbuilder-python
343
microsoft__botbuilder-python-343
[ "337" ]
392a5d45bd5c7c61361732eb9d948e60694aef3b
diff --git a/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py b/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py --- a/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py +++ b/libraries/botbuilder-azure/botbuilder/azure/cosmosdb_storage.py @@ -10,9 +10,11 @@ from typing import Dict, List from threading import Semaphore import json +from jsonpickle.pickler import Pickler +from jsonpickle.unpickler import Unpickler import azure.cosmos.cosmos_client as cosmos_client # pylint: disable=no-name-in-module,import-error import azure.cosmos.errors as cosmos_errors # pylint: disable=no-name-in-module,import-error -from botbuilder.core.storage import Storage, StoreItem +from botbuilder.core.storage import Storage class CosmosDbConfig: @@ -144,7 +146,7 @@ async def read(self, keys: List[str]) -> Dict[str, object]: results = list( self.client.QueryItems(self.__container_link, query, options) ) - # return a dict with a key and a StoreItem + # return a dict with a key and an object return {r.get("realId"): self.__create_si(r) for r in results} # No keys passed in, no result to return. @@ -152,7 +154,7 @@ async def read(self, keys: List[str]) -> Dict[str, object]: except TypeError as error: raise error - async def write(self, changes: Dict[str, StoreItem]): + async def write(self, changes: Dict[str, object]): """Save storeitems to storage. :param changes: @@ -224,22 +226,25 @@ async def delete(self, keys: List[str]): except TypeError as error: raise error - def __create_si(self, result) -> StoreItem: - """Create a StoreItem from a result out of CosmosDB. + def __create_si(self, result) -> object: + """Create an object from a result out of CosmosDB. :param result: - :return StoreItem: + :return object: """ # get the document item from the result and turn into a dict doc = result.get("document") - # readd the e_tag from Cosmos + # read the e_tag from Cosmos if result.get("_etag"): doc["e_tag"] = result["_etag"] - # create and return the StoreItem - return StoreItem(**doc) - def __create_dict(self, store_item: StoreItem) -> Dict: - """Return the dict of a StoreItem. + result_obj = Unpickler().restore(doc) + + # create and return the object + return result_obj + + def __create_dict(self, store_item: object) -> Dict: + """Return the dict of an object. This eliminates non_magic attributes and the e_tag. @@ -247,13 +252,12 @@ def __create_dict(self, store_item: StoreItem) -> Dict: :return dict: """ # read the content - non_magic_attr = [ - attr - for attr in dir(store_item) - if not attr.startswith("_") or attr.__eq__("e_tag") - ] + json_dict = Pickler().flatten(store_item) + if "e_tag" in json_dict: + del json_dict["e_tag"] + # loop through attributes and write and return a dict - return {attr: getattr(store_item, attr) for attr in non_magic_attr} + return json_dict def __item_link(self, identifier) -> str: """Return the item link of a item in the container. diff --git a/libraries/botbuilder-azure/setup.py b/libraries/botbuilder-azure/setup.py --- a/libraries/botbuilder-azure/setup.py +++ b/libraries/botbuilder-azure/setup.py @@ -9,6 +9,7 @@ "azure-storage-blob>=2.1.0", "botbuilder-schema>=4.4.0b1", "botframework-connector>=4.4.0b1", + "jsonpickle>=1.2", ] TEST_REQUIRES = ["aiounittest>=1.1.0"]
Fix serialization on state layer The current version of the sdk makes a very naive approach on serialization, which could arise potential issues in the storage process (including the behavior of the Dialog system).
2019-10-15T21:35:16
microsoft/botbuilder-python
378
microsoft__botbuilder-python-378
[ "382" ]
e5f445b74943128474457659d6a868bf47efef48
diff --git a/libraries/botframework-connector/botframework/connector/auth/microsoft_app_credentials.py b/libraries/botframework-connector/botframework/connector/auth/microsoft_app_credentials.py --- a/libraries/botframework-connector/botframework/connector/auth/microsoft_app_credentials.py +++ b/libraries/botframework-connector/botframework/connector/auth/microsoft_app_credentials.py @@ -3,8 +3,9 @@ from datetime import datetime, timedelta from urllib.parse import urlparse -from msrest.authentication import BasicTokenAuthentication, Authentication import requests + +from msrest.authentication import Authentication from .constants import Constants # TODO: Decide to move this to Constants or viceversa (when porting OAuth) @@ -82,20 +83,25 @@ def __init__(self, app_id: str, password: str, channel_auth_tenant: str = None): self.oauth_scope = AUTH_SETTINGS["refreshScope"] self.token_cache_key = app_id + "-cache" - def signed_session(self) -> requests.Session: # pylint: disable=arguments-differ + # pylint: disable=arguments-differ + def signed_session(self, session: requests.Session = None) -> requests.Session: """ Gets the signed session. :returns: Signed requests.Session object """ - auth_token = self.get_access_token() - - basic_authentication = BasicTokenAuthentication({"access_token": auth_token}) - session = basic_authentication.signed_session() + if not session: + session = requests.Session() # If there is no microsoft_app_id and no self.microsoft_app_password, then there shouldn't # be an "Authorization" header on the outgoing activity. if not self.microsoft_app_id and not self.microsoft_app_password: - del session.headers["Authorization"] + session.headers.pop("Authorization", None) + + elif not session.headers.get("Authorization"): + auth_token = self.get_access_token() + header = "{} {}".format("Bearer", auth_token) + session.headers["Authorization"] = header + return session def get_access_token(self, force_refresh: bool = False) -> str:
Fix session injection message from msrest Support session injection in MicrosoftAppCredentials fixing the warning of: Your credentials class does not support session injection. Performance will not be at the maximum.
2019-10-30T01:24:02
microsoft/botbuilder-python
383
microsoft__botbuilder-python-383
[ "414" ]
fbf8a1556709f669d8cceccc32b50b9c174f2fcf
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_factory.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_factory.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_factory.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_factory.py @@ -69,7 +69,7 @@ def for_channel( # If the titles are short and there are 3 or less choices we'll use an inline list. return ChoiceFactory.inline(choices, text, speak, options) # Show a numbered list. - return [choices, text, speak, options] + return ChoiceFactory.list_style(choices, text, speak, options) @staticmethod def inline(
ChoiceFactory.for_channel could erroneously return a List instead of an Activity Found in 4.5b5. ChoiceFactory.for_channel could return a List instead of the expected Activity when the type should have defaulted to a list style. [bug]
2019-10-31T11:42:52
microsoft/botbuilder-python
426
microsoft__botbuilder-python-426
[ "425" ]
9ed74df0ed112b33dd3845383ee59130ff15d9d6
diff --git a/samples/45.state-management/bots/state_management_bot.py b/samples/45.state-management/bots/state_management_bot.py --- a/samples/45.state-management/bots/state_management_bot.py +++ b/samples/45.state-management/bots/state_management_bot.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. import time -import pytz from datetime import datetime from botbuilder.core import ActivityHandler, ConversationState, TurnContext, UserState @@ -25,10 +24,10 @@ def __init__(self, conversation_state: ConversationState, user_state: UserState) self.conversation_state = conversation_state self.user_state = user_state - self.conversation_data = self.conversation_state.create_property( + self.conversation_data_accessor = self.conversation_state.create_property( "ConversationData" ) - self.user_profile = self.conversation_state.create_property("UserProfile") + self.user_profile_accessor = self.user_state.create_property("UserProfile") async def on_turn(self, turn_context: TurnContext): await super().on_turn(turn_context) @@ -47,8 +46,8 @@ async def on_members_added_activity( async def on_message_activity(self, turn_context: TurnContext): # Get the state properties from the turn context. - user_profile = await self.user_profile.get(turn_context, UserProfile) - conversation_data = await self.conversation_data.get( + user_profile = await self.user_profile_accessor.get(turn_context, UserProfile) + conversation_data = await self.conversation_data_accessor.get( turn_context, ConversationData )
Bug in 45.state-management sample To create the user profile property , it should refer the UserState but in the sample its referring the conversationstate. Current code : self.user_profile = self.conversation_state.create_property("UserProfile") Expected code : self.user_profile = self.user_state.create_property("UserProfile")
Thanks! Pushing a fix to master shortly.
2019-11-12T14:49:55
microsoft/botbuilder-python
683
microsoft__botbuilder-python-683
[ "606" ]
3212a6f3aa077f7d1a08df0846250ad22ea03561
diff --git a/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py b/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py --- a/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py +++ b/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py @@ -222,6 +222,9 @@ async def continue_conversation( context = TurnContext(self, get_continuation_activity(reference)) context.turn_state[BOT_IDENTITY_KEY] = claims_identity context.turn_state["BotCallbackHandler"] = callback + await self._ensure_channel_connector_client_is_created( + reference.service_url, claims_identity + ) return await self.run_pipeline(context, callback) async def create_conversation( @@ -965,3 +968,31 @@ def check_emulating_oauth_cards(self, context: TurnContext): ) ): self._is_emulating_oauth_cards = True + + async def _ensure_channel_connector_client_is_created( + self, service_url: str, claims_identity: ClaimsIdentity + ): + # Ensure we have a default ConnectorClient and MSAppCredentials instance for the audience. + audience = claims_identity.claims.get(AuthenticationConstants.AUDIENCE_CLAIM) + + if ( + not audience + or AuthenticationConstants.TO_BOT_FROM_CHANNEL_TOKEN_ISSUER != audience + ): + # We create a default connector for audiences that are not coming from + # the default https://api.botframework.com audience. + # We create a default claim that contains only the desired audience. + default_connector_claims = { + AuthenticationConstants.AUDIENCE_CLAIM: audience + } + connector_claims_identity = ClaimsIdentity( + claims=default_connector_claims, is_authenticated=True + ) + + await self.create_connector_client(service_url, connector_claims_identity) + + if SkillValidation.is_skill_claim(claims_identity.claims): + # Add the channel service URL to the trusted services list so we can send messages back. + # the service URL for skills is trusted because it is applied by the + # SkillHandler based on the original request received by the root bot + MicrosoftAppCredentials.trust_service_url(service_url)
Channel returns 401 on ContinueConversationAsync calls ## Version 4.7.0 ## Describe the bug See https://github.com/microsoft/botbuilder-dotnet/issues/3245 for details on the issue. ## To Reproduce Python uses different caching mechanisms than C#, we need to test and see if we can repro the issue here.
2020-01-31T21:35:39
microsoft/botbuilder-python
689
microsoft__botbuilder-python-689
[ "544" ]
64e2d12c197c7313e99d3f6ccb724765bdba4b67
diff --git a/libraries/botbuilder-core/botbuilder/core/turn_context.py b/libraries/botbuilder-core/botbuilder/core/turn_context.py --- a/libraries/botbuilder-core/botbuilder/core/turn_context.py +++ b/libraries/botbuilder-core/botbuilder/core/turn_context.py @@ -1,383 +1,383 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -import re -from copy import copy, deepcopy -from datetime import datetime -from typing import List, Callable, Union, Dict -from botbuilder.schema import ( - Activity, - ActivityTypes, - ConversationReference, - InputHints, - Mention, - ResourceResponse, -) - - -class TurnContext: - def __init__(self, adapter_or_context, request: Activity = None): - """ - Creates a new TurnContext instance. - :param adapter_or_context: - :param request: - """ - if isinstance(adapter_or_context, TurnContext): - adapter_or_context.copy_to(self) - else: - self.adapter = adapter_or_context - self._activity = request - self.responses: List[Activity] = [] - self._services: dict = {} - self._on_send_activities: Callable[ - ["TurnContext", List[Activity], Callable], List[ResourceResponse] - ] = [] - self._on_update_activity: Callable[ - ["TurnContext", Activity, Callable], ResourceResponse - ] = [] - self._on_delete_activity: Callable[ - ["TurnContext", ConversationReference, Callable], None - ] = [] - self._responded: bool = False - - if self.adapter is None: - raise TypeError("TurnContext must be instantiated with an adapter.") - if self.activity is None: - raise TypeError( - "TurnContext must be instantiated with a request parameter of type Activity." - ) - - self._turn_state = {} - - @property - def turn_state(self) -> Dict[str, object]: - return self._turn_state - - 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. - :param context: - :return: - """ - for attribute in [ - "adapter", - "activity", - "_responded", - "_services", - "_on_send_activities", - "_on_update_activity", - "_on_delete_activity", - ]: - setattr(context, attribute, getattr(self, attribute)) - - @property - def activity(self): - """ - The received activity. - :return: - """ - return self._activity - - @activity.setter - def activity(self, value): - """ - 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( - "TurnContext: cannot set `activity` to a type other than Activity." - ) - self._activity = value - - @property - def responded(self) -> bool: - """ - If `true` at least one response has been sent for the current turn of conversation. - :return: - """ - return self._responded - - @responded.setter - def responded(self, value: bool): - if not value: - raise ValueError("TurnContext: cannot set TurnContext.responded to False.") - self._responded = True - - @property - def services(self): - """ - Map of services and other values cached for the lifetime of the turn. - :return: - """ - return self._services - - def get(self, key: str) -> object: - if not key or not isinstance(key, str): - raise TypeError('"key" must be a valid string.') - try: - return self._services[key] - except KeyError: - raise KeyError("%s not found in TurnContext._services." % key) - - def has(self, key: str) -> bool: - """ - Returns True is set() has been called for a key. The cached value may be of type 'None'. - :param key: - :return: - """ - if key in self._services: - return True - return False - - def set(self, key: str, value: object) -> None: - """ - Caches a value for the lifetime of the current turn. - :param key: - :param value: - :return: - """ - if not key or not isinstance(key, str): - raise KeyError('"key" must be a valid string.') - - self._services[key] = value - - async def send_activity( - self, - activity_or_text: Union[Activity, str], - speak: str = None, - input_hint: str = None, - ) -> ResourceResponse: - """ - Sends a single activity or message to the user. - :param activity_or_text: - :return: - """ - if isinstance(activity_or_text, str): - activity_or_text = Activity( - text=activity_or_text, - input_hint=input_hint or InputHints.accepting_input, - speak=speak, - ) - - result = await self.send_activities([activity_or_text]) - return result[0] if result else None - - async def send_activities( - self, activities: List[Activity] - ) -> List[ResourceResponse]: - sent_non_trace_activity = False - ref = TurnContext.get_conversation_reference(self.activity) - - def activity_validator(activity: Activity) -> Activity: - if not getattr(activity, "type", None): - activity.type = ActivityTypes.message - if activity.type != ActivityTypes.trace: - nonlocal sent_non_trace_activity - sent_non_trace_activity = True - if not activity.input_hint: - activity.input_hint = "acceptingInput" - activity.id = None - return activity - - output = [ - activity_validator( - TurnContext.apply_conversation_reference(deepcopy(act), ref) - ) - for act in activities - ] - - async def logic(): - responses = await self.adapter.send_activities(self, output) - if sent_non_trace_activity: - self.responded = True - return responses - - return await self._emit(self._on_send_activities, output, logic()) - - async def update_activity(self, activity: Activity): - """ - Replaces an existing activity. - :param activity: - :return: - """ - reference = TurnContext.get_conversation_reference(self.activity) - - return await self._emit( - self._on_update_activity, - TurnContext.apply_conversation_reference(activity, reference), - self.adapter.update_activity(self, activity), - ) - - async def delete_activity(self, id_or_reference: Union[str, ConversationReference]): - """ - Deletes an existing activity. - :param id_or_reference: - :return: - """ - if isinstance(id_or_reference, str): - 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) -> "TurnContext": - """ - Registers a handler to be notified of and potentially intercept the sending of activities. - :param handler: - :return: - """ - self._on_send_activities.append(handler) - return self - - def on_update_activity(self, handler) -> "TurnContext": - """ - Registers a handler to be notified of and potentially intercept an activity being updated. - :param handler: - :return: - """ - self._on_update_activity.append(handler) - return self - - def on_delete_activity(self, handler) -> "TurnContext": - """ - Registers a handler to be notified of and potentially intercept an activity being deleted. - :param handler: - :return: - """ - self._on_delete_activity.append(handler) - return self - - async def _emit(self, plugins, arg, logic): - handlers = copy(plugins) - - async def emit_next(i: int): - context = self - try: - if i < len(handlers): - - async def next_handler(): - await emit_next(i + 1) - - await handlers[i](context, arg, next_handler) - - except Exception as error: - raise error - - await emit_next(0) - # logic does not use parentheses because it's a coroutine - return await logic - - async def send_trace_activity( - self, name: str, value: object, value_type: str, label: str - ) -> ResourceResponse: - trace_activity = Activity( - type=ActivityTypes.trace, - timestamp=datetime.utcnow(), - name=name, - value=value, - value_type=value_type, - label=label, - ) - - return await self.send_activity(trace_activity) - - @staticmethod - def get_conversation_reference(activity: Activity) -> ConversationReference: - """ - Returns the conversation reference for an activity. This can be saved as a plain old JSON - object and then later used to message the user proactively. - - Usage Example: - reference = TurnContext.get_conversation_reference(context.request) - :param activity: - :return: - """ - return ConversationReference( - activity_id=activity.id, - user=copy(activity.from_property), - bot=copy(activity.recipient), - conversation=copy(activity.conversation), - channel_id=activity.channel_id, - service_url=activity.service_url, - ) - - @staticmethod - def apply_conversation_reference( - activity: Activity, reference: ConversationReference, is_incoming: bool = False - ) -> Activity: - """ - Updates an activity with the delivery information from a conversation reference. Calling - this after get_conversation_reference on an incoming activity - will properly address the reply to a received activity. - :param activity: - :param reference: - :param is_incoming: - :return: - """ - activity.channel_id = reference.channel_id - activity.service_url = reference.service_url - activity.conversation = reference.conversation - if is_incoming: - activity.from_property = reference.user - activity.recipient = reference.bot - if reference.activity_id: - activity.id = reference.activity_id - else: - activity.from_property = reference.bot - activity.recipient = reference.user - if reference.activity_id: - activity.reply_to_id = reference.activity_id - - return activity - - @staticmethod - def get_reply_conversation_reference( - activity: Activity, reply: ResourceResponse - ) -> ConversationReference: - reference: ConversationReference = TurnContext.get_conversation_reference( - activity - ) - - # Update the reference with the new outgoing Activity's id. - reference.activity_id = reply.id - - return reference - - @staticmethod - def remove_recipient_mention(activity: Activity) -> str: - return TurnContext.remove_mention_text(activity, activity.recipient.id) - - @staticmethod - def remove_mention_text(activity: Activity, identifier: str) -> str: - mentions = TurnContext.get_mentions(activity) - for mention in mentions: - if mention.additional_properties["mentioned"]["id"] == identifier: - mention_name_match = re.match( - r"<at(.*)>(.*?)<\/at>", - mention.additional_properties["text"], - re.IGNORECASE, - ) - if mention_name_match: - activity.text = re.sub( - mention_name_match.groups()[1], "", activity.text - ) - activity.text = re.sub(r"<at><\/at>", "", activity.text) - return activity.text - - @staticmethod - def get_mentions(activity: Activity) -> List[Mention]: - result: List[Mention] = [] - if activity.entities is not None: - for entity in activity.entities: - if entity.type.lower() == "mention": - result.append(entity) - - return result +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import re +from copy import copy, deepcopy +from datetime import datetime +from typing import List, Callable, Union, Dict +from botbuilder.schema import ( + Activity, + ActivityTypes, + ConversationReference, + InputHints, + Mention, + ResourceResponse, +) + + +class TurnContext: + def __init__(self, adapter_or_context, request: Activity = None): + """ + Creates a new TurnContext instance. + :param adapter_or_context: + :param request: + """ + if isinstance(adapter_or_context, TurnContext): + adapter_or_context.copy_to(self) + else: + self.adapter = adapter_or_context + self._activity = request + self.responses: List[Activity] = [] + self._services: dict = {} + self._on_send_activities: Callable[ + ["TurnContext", List[Activity], Callable], List[ResourceResponse] + ] = [] + self._on_update_activity: Callable[ + ["TurnContext", Activity, Callable], ResourceResponse + ] = [] + self._on_delete_activity: Callable[ + ["TurnContext", ConversationReference, Callable], None + ] = [] + self._responded: bool = False + + if self.adapter is None: + raise TypeError("TurnContext must be instantiated with an adapter.") + if self.activity is None: + raise TypeError( + "TurnContext must be instantiated with a request parameter of type Activity." + ) + + self._turn_state = {} + + @property + def turn_state(self) -> Dict[str, object]: + return self._turn_state + + 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. + :param context: + :return: + """ + for attribute in [ + "adapter", + "activity", + "_responded", + "_services", + "_on_send_activities", + "_on_update_activity", + "_on_delete_activity", + ]: + setattr(context, attribute, getattr(self, attribute)) + + @property + def activity(self): + """ + The received activity. + :return: + """ + return self._activity + + @activity.setter + def activity(self, value): + """ + 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( + "TurnContext: cannot set `activity` to a type other than Activity." + ) + self._activity = value + + @property + def responded(self) -> bool: + """ + If `true` at least one response has been sent for the current turn of conversation. + :return: + """ + return self._responded + + @responded.setter + def responded(self, value: bool): + if not value: + raise ValueError("TurnContext: cannot set TurnContext.responded to False.") + self._responded = True + + @property + def services(self): + """ + Map of services and other values cached for the lifetime of the turn. + :return: + """ + return self._services + + def get(self, key: str) -> object: + if not key or not isinstance(key, str): + raise TypeError('"key" must be a valid string.') + try: + return self._services[key] + except KeyError: + raise KeyError("%s not found in TurnContext._services." % key) + + def has(self, key: str) -> bool: + """ + Returns True is set() has been called for a key. The cached value may be of type 'None'. + :param key: + :return: + """ + if key in self._services: + return True + return False + + def set(self, key: str, value: object) -> None: + """ + Caches a value for the lifetime of the current turn. + :param key: + :param value: + :return: + """ + if not key or not isinstance(key, str): + raise KeyError('"key" must be a valid string.') + + self._services[key] = value + + async def send_activity( + self, + activity_or_text: Union[Activity, str], + speak: str = None, + input_hint: str = None, + ) -> ResourceResponse: + """ + Sends a single activity or message to the user. + :param activity_or_text: + :return: + """ + if isinstance(activity_or_text, str): + activity_or_text = Activity( + text=activity_or_text, + input_hint=input_hint or InputHints.accepting_input, + speak=speak, + ) + + result = await self.send_activities([activity_or_text]) + return result[0] if result else None + + async def send_activities( + self, activities: List[Activity] + ) -> List[ResourceResponse]: + sent_non_trace_activity = False + ref = TurnContext.get_conversation_reference(self.activity) + + def activity_validator(activity: Activity) -> Activity: + if not getattr(activity, "type", None): + activity.type = ActivityTypes.message + if activity.type != ActivityTypes.trace: + nonlocal sent_non_trace_activity + sent_non_trace_activity = True + if not activity.input_hint: + activity.input_hint = "acceptingInput" + activity.id = None + return activity + + output = [ + activity_validator( + TurnContext.apply_conversation_reference(deepcopy(act), ref) + ) + for act in activities + ] + + async def logic(): + responses = await self.adapter.send_activities(self, output) + if sent_non_trace_activity: + self.responded = True + return responses + + return await self._emit(self._on_send_activities, output, logic()) + + async def update_activity(self, activity: Activity): + """ + Replaces an existing activity. + :param activity: + :return: + """ + reference = TurnContext.get_conversation_reference(self.activity) + + return await self._emit( + self._on_update_activity, + TurnContext.apply_conversation_reference(activity, reference), + self.adapter.update_activity(self, activity), + ) + + async def delete_activity(self, id_or_reference: Union[str, ConversationReference]): + """ + Deletes an existing activity. + :param id_or_reference: + :return: + """ + if isinstance(id_or_reference, str): + 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) -> "TurnContext": + """ + Registers a handler to be notified of and potentially intercept the sending of activities. + :param handler: + :return: + """ + self._on_send_activities.append(handler) + return self + + def on_update_activity(self, handler) -> "TurnContext": + """ + Registers a handler to be notified of and potentially intercept an activity being updated. + :param handler: + :return: + """ + self._on_update_activity.append(handler) + return self + + def on_delete_activity(self, handler) -> "TurnContext": + """ + Registers a handler to be notified of and potentially intercept an activity being deleted. + :param handler: + :return: + """ + self._on_delete_activity.append(handler) + return self + + async def _emit(self, plugins, arg, logic): + handlers = copy(plugins) + + async def emit_next(i: int): + context = self + try: + if i < len(handlers): + + async def next_handler(): + await emit_next(i + 1) + + await handlers[i](context, arg, next_handler) + + except Exception as error: + raise error + + await emit_next(0) + # logic does not use parentheses because it's a coroutine + return await logic + + async def send_trace_activity( + self, name: str, value: object, value_type: str, label: str + ) -> ResourceResponse: + trace_activity = Activity( + type=ActivityTypes.trace, + timestamp=datetime.utcnow(), + name=name, + value=value, + value_type=value_type, + label=label, + ) + + return await self.send_activity(trace_activity) + + @staticmethod + def get_conversation_reference(activity: Activity) -> ConversationReference: + """ + Returns the conversation reference for an activity. This can be saved as a plain old JSON + object and then later used to message the user proactively. + + Usage Example: + reference = TurnContext.get_conversation_reference(context.request) + :param activity: + :return: + """ + return ConversationReference( + activity_id=activity.id, + user=copy(activity.from_property), + bot=copy(activity.recipient), + conversation=copy(activity.conversation), + channel_id=activity.channel_id, + service_url=activity.service_url, + ) + + @staticmethod + def apply_conversation_reference( + activity: Activity, reference: ConversationReference, is_incoming: bool = False + ) -> Activity: + """ + Updates an activity with the delivery information from a conversation reference. Calling + this after get_conversation_reference on an incoming activity + will properly address the reply to a received activity. + :param activity: + :param reference: + :param is_incoming: + :return: + """ + activity.channel_id = reference.channel_id + activity.service_url = reference.service_url + activity.conversation = reference.conversation + if is_incoming: + activity.from_property = reference.user + activity.recipient = reference.bot + if reference.activity_id: + activity.id = reference.activity_id + else: + activity.from_property = reference.bot + activity.recipient = reference.user + if reference.activity_id: + activity.reply_to_id = reference.activity_id + + return activity + + @staticmethod + def get_reply_conversation_reference( + activity: Activity, reply: ResourceResponse + ) -> ConversationReference: + reference: ConversationReference = TurnContext.get_conversation_reference( + activity + ) + + # Update the reference with the new outgoing Activity's id. + reference.activity_id = reply.id + + return reference + + @staticmethod + def remove_recipient_mention(activity: Activity) -> str: + return TurnContext.remove_mention_text(activity, activity.recipient.id) + + @staticmethod + def remove_mention_text(activity: Activity, identifier: str) -> str: + mentions = TurnContext.get_mentions(activity) + for mention in mentions: + if mention.additional_properties["mentioned"]["id"] == identifier: + mention_name_match = re.match( + r"<at(.*)>(.*?)<\/at>", + re.escape(mention.additional_properties["text"]), + re.IGNORECASE, + ) + if mention_name_match: + activity.text = re.sub( + mention_name_match.groups()[1], "", activity.text + ) + activity.text = re.sub(r"<at><\/at>", "", activity.text) + return activity.text + + @staticmethod + def get_mentions(activity: Activity) -> List[Mention]: + result: List[Mention] = [] + if activity.entities is not None: + for entity in activity.entities: + if entity.type.lower() == "mention": + result.append(entity) + + return result
diff --git a/libraries/botbuilder-core/tests/test_turn_context.py b/libraries/botbuilder-core/tests/test_turn_context.py --- a/libraries/botbuilder-core/tests/test_turn_context.py +++ b/libraries/botbuilder-core/tests/test_turn_context.py @@ -1,351 +1,372 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -from typing import Callable, List -import aiounittest - -from botbuilder.schema import ( - Activity, - ActivityTypes, - ChannelAccount, - ConversationAccount, - Entity, - Mention, - ResourceResponse, -) -from botbuilder.core import BotAdapter, MessageFactory, TurnContext - -ACTIVITY = Activity( - id="1234", - type="message", - text="test", - from_property=ChannelAccount(id="user", name="User Name"), - recipient=ChannelAccount(id="bot", name="Bot Name"), - conversation=ConversationAccount(id="convo", name="Convo Name"), - channel_id="UnitTest", - service_url="https://example.org", -) - - -class SimpleAdapter(BotAdapter): - async def send_activities(self, context, activities) -> List[ResourceResponse]: - responses = [] - assert context is not None - assert activities is not None - assert isinstance(activities, list) - assert activities - for (idx, activity) in enumerate(activities): # pylint: disable=unused-variable - assert isinstance(activity, Activity) - assert activity.type == "message" or activity.type == ActivityTypes.trace - responses.append(ResourceResponse(id="5678")) - return responses - - async def update_activity(self, context, activity): - assert context is not None - assert activity is not None - return ResourceResponse(id=activity.id) - - async def delete_activity(self, context, reference): - assert context is not None - assert reference is not None - assert reference.activity_id == ACTIVITY.id - - -class TestBotContext(aiounittest.AsyncTestCase): - def test_should_create_context_with_request_and_adapter(self): - TurnContext(SimpleAdapter(), ACTIVITY) - - def test_should_not_create_context_without_request(self): - try: - TurnContext(SimpleAdapter(), None) - except TypeError: - pass - except Exception as error: - raise error - - def test_should_not_create_context_without_adapter(self): - try: - TurnContext(None, ACTIVITY) - except TypeError: - pass - except Exception as error: - raise error - - def test_should_create_context_with_older_context(self): - context = TurnContext(SimpleAdapter(), ACTIVITY) - TurnContext(context) - - def test_copy_to_should_copy_all_references(self): - # pylint: disable=protected-access - old_adapter = SimpleAdapter() - old_activity = Activity(id="2", type="message", text="test copy") - old_context = TurnContext(old_adapter, old_activity) - old_context.responded = True - - async def send_activities_handler(context, activities, next_handler): - assert context is not None - assert activities is not None - assert next_handler is not None - await next_handler - - async def delete_activity_handler(context, reference, next_handler): - assert context is not None - assert reference is not None - assert next_handler is not None - await next_handler - - async def update_activity_handler(context, activity, next_handler): - assert context is not None - assert activity is not None - assert next_handler is not None - await next_handler - - old_context.on_send_activities(send_activities_handler) - old_context.on_delete_activity(delete_activity_handler) - old_context.on_update_activity(update_activity_handler) - - adapter = SimpleAdapter() - new_context = TurnContext(adapter, ACTIVITY) - assert not new_context._on_send_activities # pylint: disable=protected-access - assert not new_context._on_update_activity # pylint: disable=protected-access - assert not new_context._on_delete_activity # pylint: disable=protected-access - - old_context.copy_to(new_context) - - assert new_context.adapter == old_adapter - assert new_context.activity == old_activity - assert new_context.responded is True - assert ( - len(new_context._on_send_activities) == 1 - ) # pylint: disable=protected-access - assert ( - len(new_context._on_update_activity) == 1 - ) # pylint: disable=protected-access - assert ( - len(new_context._on_delete_activity) == 1 - ) # pylint: disable=protected-access - - def test_responded_should_be_automatically_set_to_false(self): - context = TurnContext(SimpleAdapter(), ACTIVITY) - assert context.responded is False - - def test_should_be_able_to_set_responded_to_true(self): - 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 = TurnContext(SimpleAdapter(), ACTIVITY) - try: - context.responded = False - except ValueError: - pass - except Exception as error: - raise error - - async def test_should_call_on_delete_activity_handlers_before_deletion(self): - context = TurnContext(SimpleAdapter(), ACTIVITY) - called = False - - async def delete_handler(context, reference, next_handler_coroutine): - nonlocal called - called = True - assert reference is not None - assert context is not None - assert reference.activity_id == "1234" - await next_handler_coroutine() - - context.on_delete_activity(delete_handler) - await context.delete_activity(ACTIVITY.id) - assert called is True - - async def test_should_call_multiple_on_delete_activity_handlers_in_order(self): - context = TurnContext(SimpleAdapter(), ACTIVITY) - called_first = False - called_second = False - - async def first_delete_handler(context, reference, next_handler_coroutine): - nonlocal called_first, called_second - assert ( - called_first is False - ), "called_first should not be True before first_delete_handler is called." - called_first = True - assert ( - called_second is False - ), "Second on_delete_activity handler was called before first." - assert reference is not None - assert context is not None - assert reference.activity_id == "1234" - await next_handler_coroutine() - - async def second_delete_handler(context, reference, next_handler_coroutine): - nonlocal called_first, called_second - assert called_first - assert ( - called_second is False - ), "called_second was set to True before second handler was called." - called_second = True - assert reference is not None - assert context is not None - assert reference.activity_id == "1234" - await next_handler_coroutine() - - context.on_delete_activity(first_delete_handler) - context.on_delete_activity(second_delete_handler) - await context.delete_activity(ACTIVITY.id) - assert called_first is True - assert called_second is True - - async def test_should_call_send_on_activities_handler_before_send(self): - context = TurnContext(SimpleAdapter(), ACTIVITY) - called = False - - async def send_handler(context, activities, next_handler_coroutine): - nonlocal called - called = True - assert activities is not None - assert context is not None - assert not activities[0].id - await next_handler_coroutine() - - context.on_send_activities(send_handler) - await context.send_activity(ACTIVITY) - assert called is True - - async def test_should_call_on_update_activity_handler_before_update(self): - context = TurnContext(SimpleAdapter(), ACTIVITY) - called = False - - async def update_handler(context, activity, next_handler_coroutine): - nonlocal called - called = True - assert activity is not None - assert context is not None - assert activity.id == "1234" - await next_handler_coroutine() - - context.on_update_activity(update_handler) - await context.update_activity(ACTIVITY) - assert called is True - - async def test_update_activity_should_apply_conversation_reference(self): - activity_id = "activity ID" - context = TurnContext(SimpleAdapter(), ACTIVITY) - called = False - - async def update_handler(context, activity, next_handler_coroutine): - nonlocal called - called = True - assert context is not None - assert activity.id == activity_id - assert activity.conversation.id == ACTIVITY.conversation.id - await next_handler_coroutine() - - context.on_update_activity(update_handler) - new_activity = MessageFactory.text("test text") - new_activity.id = activity_id - update_result = await context.update_activity(new_activity) - assert called is True - assert update_result.id == activity_id - - def test_get_conversation_reference_should_return_valid_reference(self): - reference = TurnContext.get_conversation_reference(ACTIVITY) - - assert reference.activity_id == ACTIVITY.id - assert reference.user == ACTIVITY.from_property - assert reference.bot == ACTIVITY.recipient - assert reference.conversation == ACTIVITY.conversation - assert reference.channel_id == ACTIVITY.channel_id - assert reference.service_url == ACTIVITY.service_url - - def test_apply_conversation_reference_should_return_prepare_reply_when_is_incoming_is_false( - self, - ): - 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 - assert reply.conversation == ACTIVITY.conversation - assert reply.service_url == ACTIVITY.service_url - assert reply.channel_id == ACTIVITY.channel_id - - def test_apply_conversation_reference_when_is_incoming_is_true_should_not_prepare_a_reply( - self, - ): - 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 - assert reply.conversation == ACTIVITY.conversation - assert reply.service_url == ACTIVITY.service_url - assert reply.channel_id == ACTIVITY.channel_id - - async def test_should_get_conversation_reference_using_get_reply_conversation_reference( - self, - ): - context = TurnContext(SimpleAdapter(), ACTIVITY) - reply = await context.send_activity("test") - - assert reply.id, "reply has an id" - - reference = TurnContext.get_reply_conversation_reference( - context.activity, reply - ) - - assert reference.activity_id, "reference has an activity id" - assert ( - reference.activity_id == reply.id - ), "reference id matches outgoing reply id" - - def test_should_remove_at_mention_from_activity(self): - activity = Activity( - type="message", - text="<at>TestOAuth619</at> test activity", - recipient=ChannelAccount(id="TestOAuth619"), - entities=[ - Entity().deserialize( - Mention( - type="mention", - text="<at>TestOAuth619</at>", - mentioned=ChannelAccount(name="Bot", id="TestOAuth619"), - ).serialize() - ) - ], - ) - - text = TurnContext.remove_recipient_mention(activity) - - assert text, " test activity" - assert activity.text, " test activity" - - async def test_should_send_a_trace_activity(self): - context = TurnContext(SimpleAdapter(), ACTIVITY) - called = False - - # pylint: disable=unused-argument - async def aux_func( - ctx: TurnContext, activities: List[Activity], next: Callable - ): - nonlocal called - called = True - assert isinstance(activities, list), "activities not array." - assert len(activities) == 1, "invalid count of activities." - assert activities[0].type == ActivityTypes.trace, "type wrong." - assert activities[0].name == "name-text", "name wrong." - assert activities[0].value == "value-text", "value worng." - assert activities[0].value_type == "valueType-text", "valeuType wrong." - assert activities[0].label == "label-text", "label wrong." - return [] - - context.on_send_activities(aux_func) - await context.send_trace_activity( - "name-text", "value-text", "valueType-text", "label-text" - ) - assert called +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from typing import Callable, List +import aiounittest + +from botbuilder.schema import ( + Activity, + ActivityTypes, + ChannelAccount, + ConversationAccount, + Entity, + Mention, + ResourceResponse, +) +from botbuilder.core import BotAdapter, MessageFactory, TurnContext + +ACTIVITY = Activity( + id="1234", + type="message", + text="test", + from_property=ChannelAccount(id="user", name="User Name"), + recipient=ChannelAccount(id="bot", name="Bot Name"), + conversation=ConversationAccount(id="convo", name="Convo Name"), + channel_id="UnitTest", + service_url="https://example.org", +) + + +class SimpleAdapter(BotAdapter): + async def send_activities(self, context, activities) -> List[ResourceResponse]: + responses = [] + assert context is not None + assert activities is not None + assert isinstance(activities, list) + assert activities + for (idx, activity) in enumerate(activities): # pylint: disable=unused-variable + assert isinstance(activity, Activity) + assert activity.type == "message" or activity.type == ActivityTypes.trace + responses.append(ResourceResponse(id="5678")) + return responses + + async def update_activity(self, context, activity): + assert context is not None + assert activity is not None + return ResourceResponse(id=activity.id) + + async def delete_activity(self, context, reference): + assert context is not None + assert reference is not None + assert reference.activity_id == ACTIVITY.id + + +class TestBotContext(aiounittest.AsyncTestCase): + def test_should_create_context_with_request_and_adapter(self): + TurnContext(SimpleAdapter(), ACTIVITY) + + def test_should_not_create_context_without_request(self): + try: + TurnContext(SimpleAdapter(), None) + except TypeError: + pass + except Exception as error: + raise error + + def test_should_not_create_context_without_adapter(self): + try: + TurnContext(None, ACTIVITY) + except TypeError: + pass + except Exception as error: + raise error + + def test_should_create_context_with_older_context(self): + context = TurnContext(SimpleAdapter(), ACTIVITY) + TurnContext(context) + + def test_copy_to_should_copy_all_references(self): + # pylint: disable=protected-access + old_adapter = SimpleAdapter() + old_activity = Activity(id="2", type="message", text="test copy") + old_context = TurnContext(old_adapter, old_activity) + old_context.responded = True + + async def send_activities_handler(context, activities, next_handler): + assert context is not None + assert activities is not None + assert next_handler is not None + await next_handler + + async def delete_activity_handler(context, reference, next_handler): + assert context is not None + assert reference is not None + assert next_handler is not None + await next_handler + + async def update_activity_handler(context, activity, next_handler): + assert context is not None + assert activity is not None + assert next_handler is not None + await next_handler + + old_context.on_send_activities(send_activities_handler) + old_context.on_delete_activity(delete_activity_handler) + old_context.on_update_activity(update_activity_handler) + + adapter = SimpleAdapter() + new_context = TurnContext(adapter, ACTIVITY) + assert not new_context._on_send_activities # pylint: disable=protected-access + assert not new_context._on_update_activity # pylint: disable=protected-access + assert not new_context._on_delete_activity # pylint: disable=protected-access + + old_context.copy_to(new_context) + + assert new_context.adapter == old_adapter + assert new_context.activity == old_activity + assert new_context.responded is True + assert ( + len(new_context._on_send_activities) == 1 + ) # pylint: disable=protected-access + assert ( + len(new_context._on_update_activity) == 1 + ) # pylint: disable=protected-access + assert ( + len(new_context._on_delete_activity) == 1 + ) # pylint: disable=protected-access + + def test_responded_should_be_automatically_set_to_false(self): + context = TurnContext(SimpleAdapter(), ACTIVITY) + assert context.responded is False + + def test_should_be_able_to_set_responded_to_true(self): + 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 = TurnContext(SimpleAdapter(), ACTIVITY) + try: + context.responded = False + except ValueError: + pass + except Exception as error: + raise error + + async def test_should_call_on_delete_activity_handlers_before_deletion(self): + context = TurnContext(SimpleAdapter(), ACTIVITY) + called = False + + async def delete_handler(context, reference, next_handler_coroutine): + nonlocal called + called = True + assert reference is not None + assert context is not None + assert reference.activity_id == "1234" + await next_handler_coroutine() + + context.on_delete_activity(delete_handler) + await context.delete_activity(ACTIVITY.id) + assert called is True + + async def test_should_call_multiple_on_delete_activity_handlers_in_order(self): + context = TurnContext(SimpleAdapter(), ACTIVITY) + called_first = False + called_second = False + + async def first_delete_handler(context, reference, next_handler_coroutine): + nonlocal called_first, called_second + assert ( + called_first is False + ), "called_first should not be True before first_delete_handler is called." + called_first = True + assert ( + called_second is False + ), "Second on_delete_activity handler was called before first." + assert reference is not None + assert context is not None + assert reference.activity_id == "1234" + await next_handler_coroutine() + + async def second_delete_handler(context, reference, next_handler_coroutine): + nonlocal called_first, called_second + assert called_first + assert ( + called_second is False + ), "called_second was set to True before second handler was called." + called_second = True + assert reference is not None + assert context is not None + assert reference.activity_id == "1234" + await next_handler_coroutine() + + context.on_delete_activity(first_delete_handler) + context.on_delete_activity(second_delete_handler) + await context.delete_activity(ACTIVITY.id) + assert called_first is True + assert called_second is True + + async def test_should_call_send_on_activities_handler_before_send(self): + context = TurnContext(SimpleAdapter(), ACTIVITY) + called = False + + async def send_handler(context, activities, next_handler_coroutine): + nonlocal called + called = True + assert activities is not None + assert context is not None + assert not activities[0].id + await next_handler_coroutine() + + context.on_send_activities(send_handler) + await context.send_activity(ACTIVITY) + assert called is True + + async def test_should_call_on_update_activity_handler_before_update(self): + context = TurnContext(SimpleAdapter(), ACTIVITY) + called = False + + async def update_handler(context, activity, next_handler_coroutine): + nonlocal called + called = True + assert activity is not None + assert context is not None + assert activity.id == "1234" + await next_handler_coroutine() + + context.on_update_activity(update_handler) + await context.update_activity(ACTIVITY) + assert called is True + + async def test_update_activity_should_apply_conversation_reference(self): + activity_id = "activity ID" + context = TurnContext(SimpleAdapter(), ACTIVITY) + called = False + + async def update_handler(context, activity, next_handler_coroutine): + nonlocal called + called = True + assert context is not None + assert activity.id == activity_id + assert activity.conversation.id == ACTIVITY.conversation.id + await next_handler_coroutine() + + context.on_update_activity(update_handler) + new_activity = MessageFactory.text("test text") + new_activity.id = activity_id + update_result = await context.update_activity(new_activity) + assert called is True + assert update_result.id == activity_id + + def test_get_conversation_reference_should_return_valid_reference(self): + reference = TurnContext.get_conversation_reference(ACTIVITY) + + assert reference.activity_id == ACTIVITY.id + assert reference.user == ACTIVITY.from_property + assert reference.bot == ACTIVITY.recipient + assert reference.conversation == ACTIVITY.conversation + assert reference.channel_id == ACTIVITY.channel_id + assert reference.service_url == ACTIVITY.service_url + + def test_apply_conversation_reference_should_return_prepare_reply_when_is_incoming_is_false( + self, + ): + 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 + assert reply.conversation == ACTIVITY.conversation + assert reply.service_url == ACTIVITY.service_url + assert reply.channel_id == ACTIVITY.channel_id + + def test_apply_conversation_reference_when_is_incoming_is_true_should_not_prepare_a_reply( + self, + ): + 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 + assert reply.conversation == ACTIVITY.conversation + assert reply.service_url == ACTIVITY.service_url + assert reply.channel_id == ACTIVITY.channel_id + + async def test_should_get_conversation_reference_using_get_reply_conversation_reference( + self, + ): + context = TurnContext(SimpleAdapter(), ACTIVITY) + reply = await context.send_activity("test") + + assert reply.id, "reply has an id" + + reference = TurnContext.get_reply_conversation_reference( + context.activity, reply + ) + + assert reference.activity_id, "reference has an activity id" + assert ( + reference.activity_id == reply.id + ), "reference id matches outgoing reply id" + + def test_should_remove_at_mention_from_activity(self): + activity = Activity( + type="message", + text="<at>TestOAuth619</at> test activity", + recipient=ChannelAccount(id="TestOAuth619"), + entities=[ + Entity().deserialize( + Mention( + type="mention", + text="<at>TestOAuth619</at>", + mentioned=ChannelAccount(name="Bot", id="TestOAuth619"), + ).serialize() + ) + ], + ) + + text = TurnContext.remove_recipient_mention(activity) + + assert text, " test activity" + assert activity.text, " test activity" + + def test_should_remove_at_mention_with_regex_characters(self): + activity = Activity( + type="message", + text="<at>Test (*.[]$%#^&?)</at> test activity", + recipient=ChannelAccount(id="Test (*.[]$%#^&?)"), + entities=[ + Entity().deserialize( + Mention( + type="mention", + text="<at>Test (*.[]$%#^&?)</at>", + mentioned=ChannelAccount(name="Bot", id="Test (*.[]$%#^&?)"), + ).serialize() + ) + ], + ) + + text = TurnContext.remove_recipient_mention(activity) + + assert text, " test activity" + assert activity.text, " test activity" + + async def test_should_send_a_trace_activity(self): + context = TurnContext(SimpleAdapter(), ACTIVITY) + called = False + + # pylint: disable=unused-argument + async def aux_func( + ctx: TurnContext, activities: List[Activity], next: Callable + ): + nonlocal called + called = True + assert isinstance(activities, list), "activities not array." + assert len(activities) == 1, "invalid count of activities." + assert activities[0].type == ActivityTypes.trace, "type wrong." + assert activities[0].name == "name-text", "name wrong." + assert activities[0].value == "value-text", "value worng." + assert activities[0].value_type == "valueType-text", "valeuType wrong." + assert activities[0].label == "label-text", "label wrong." + return [] + + context.on_send_activities(aux_func) + await context.send_trace_activity( + "name-text", "value-text", "valueType-text", "label-text" + ) + assert called
[PORT] Updating mention stripping scenario for Teams with special character support > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3107 Fixing bug: #3106
2020-02-03T18:10:33
microsoft/botbuilder-python
691
microsoft__botbuilder-python-691
[ "577" ]
2127e7f16ea060690fa57c796830bbbbe3c07106
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_recognizers.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_recognizers.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_recognizers.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_recognizers.py @@ -1,140 +1,141 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -from typing import List, Union -from recognizers_number import NumberModel, NumberRecognizer, OrdinalModel -from recognizers_text import Culture - - -from .choice import Choice -from .find import Find -from .find_choices_options import FindChoicesOptions -from .found_choice import FoundChoice -from .model_result import ModelResult - - -class ChoiceRecognizers: - """ Contains methods for matching user input against a list of choices. """ - - @staticmethod - def recognize_choices( - utterance: str, - choices: List[Union[str, Choice]], - options: FindChoicesOptions = None, - ) -> List[ModelResult]: - """ - Matches user input against a list of choices. - - This is layered above the `Find.find_choices()` function, and adds logic to let the user specify - their choice by index (they can say "one" to pick `choice[0]`) or ordinal position - (they can say "the second one" to pick `choice[1]`.) - The user's utterance is recognized in the following order: - - - By name using `find_choices()` - - By 1's based ordinal position. - - By 1's based index position. - - Parameters: - ----------- - - utterance: The input. - - choices: The list of choices. - - options: (Optional) Options to control the recognition strategy. - - Returns: - -------- - A list of found choices, sorted by most relevant first. - """ - if utterance is None: - utterance = "" - - # Normalize list of choices - choices_list = [ - Choice(value=choice) if isinstance(choice, str) else choice - for choice in choices - ] - - # Try finding choices by text search first - # - We only want to use a single strategy for returning results to avoid issues where utterances - # like the "the third one" or "the red one" or "the first division book" would miss-recognize as - # a numerical index or ordinal as well. - locale = options.locale if (options and options.locale) else Culture.English - matched = Find.find_choices(utterance, choices_list, options) - if not matched: - # Next try finding by ordinal - matches = ChoiceRecognizers._recognize_ordinal(utterance, locale) - - if matches: - for match in matches: - ChoiceRecognizers._match_choice_by_index( - choices_list, matched, match - ) - else: - # Finally try by numerical index - matches = ChoiceRecognizers._recognize_number(utterance, locale) - - for match in matches: - ChoiceRecognizers._match_choice_by_index( - choices_list, matched, match - ) - - # Sort any found matches by their position within the utterance. - # - The results from find_choices() are already properly sorted so we just need this - # for ordinal & numerical lookups. - matched = sorted(matched, key=lambda model_result: model_result.start) - - return matched - - @staticmethod - def _recognize_ordinal(utterance: str, culture: str) -> List[ModelResult]: - model: OrdinalModel = NumberRecognizer(culture).get_ordinal_model(culture) - - return list( - map(ChoiceRecognizers._found_choice_constructor, model.parse(utterance)) - ) - - @staticmethod - def _match_choice_by_index( - choices: List[Choice], matched: List[ModelResult], match: ModelResult - ): - try: - index: int = int(match.resolution.value) - 1 - if 0 <= index < len(choices): - choice = choices[index] - - matched.append( - ModelResult( - start=match.start, - end=match.end, - type_name="choice", - text=match.text, - resolution=FoundChoice( - value=choice.value, index=index, score=1.0 - ), - ) - ) - except: - # noop here, as in dotnet/node repos - pass - - @staticmethod - def _recognize_number(utterance: str, culture: str) -> List[ModelResult]: - model: NumberModel = NumberRecognizer(culture).get_number_model(culture) - - return list( - map(ChoiceRecognizers._found_choice_constructor, model.parse(utterance)) - ) - - @staticmethod - def _found_choice_constructor(value_model: ModelResult) -> ModelResult: - return ModelResult( - start=value_model.start, - end=value_model.end, - type_name="choice", - text=value_model.text, - resolution=FoundChoice( - value=value_model.resolution["value"], index=0, score=1.0 - ), - ) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from typing import List, Union +from recognizers_number import NumberModel, NumberRecognizer, OrdinalModel +from recognizers_text import Culture + + +from .choice import Choice +from .find import Find +from .find_choices_options import FindChoicesOptions +from .found_choice import FoundChoice +from .model_result import ModelResult + + +class ChoiceRecognizers: + """ Contains methods for matching user input against a list of choices. """ + + @staticmethod + def recognize_choices( + utterance: str, + choices: List[Union[str, Choice]], + options: FindChoicesOptions = None, + ) -> List[ModelResult]: + """ + Matches user input against a list of choices. + + This is layered above the `Find.find_choices()` function, and adds logic to let the user specify + their choice by index (they can say "one" to pick `choice[0]`) or ordinal position + (they can say "the second one" to pick `choice[1]`.) + The user's utterance is recognized in the following order: + + - By name using `find_choices()` + - By 1's based ordinal position. + - By 1's based index position. + + Parameters: + ----------- + + utterance: The input. + + choices: The list of choices. + + options: (Optional) Options to control the recognition strategy. + + Returns: + -------- + A list of found choices, sorted by most relevant first. + """ + if utterance is None: + utterance = "" + + # Normalize list of choices + choices_list = [ + Choice(value=choice) if isinstance(choice, str) else choice + for choice in choices + ] + + # Try finding choices by text search first + # - We only want to use a single strategy for returning results to avoid issues where utterances + # like the "the third one" or "the red one" or "the first division book" would miss-recognize as + # a numerical index or ordinal as well. + locale = options.locale if (options and options.locale) else Culture.English + matched = Find.find_choices(utterance, choices_list, options) + if not matched: + matches = [] + + if not options or options.recognize_ordinals: + # Next try finding by ordinal + matches = ChoiceRecognizers._recognize_ordinal(utterance, locale) + for match in matches: + ChoiceRecognizers._match_choice_by_index( + choices_list, matched, match + ) + + if not matches and (not options or options.recognize_numbers): + # Then try by numerical index + matches = ChoiceRecognizers._recognize_number(utterance, locale) + for match in matches: + ChoiceRecognizers._match_choice_by_index( + choices_list, matched, match + ) + + # Sort any found matches by their position within the utterance. + # - The results from find_choices() are already properly sorted so we just need this + # for ordinal & numerical lookups. + matched = sorted(matched, key=lambda model_result: model_result.start) + + return matched + + @staticmethod + def _recognize_ordinal(utterance: str, culture: str) -> List[ModelResult]: + model: OrdinalModel = NumberRecognizer(culture).get_ordinal_model(culture) + + return list( + map(ChoiceRecognizers._found_choice_constructor, model.parse(utterance)) + ) + + @staticmethod + def _match_choice_by_index( + choices: List[Choice], matched: List[ModelResult], match: ModelResult + ): + try: + index: int = int(match.resolution.value) - 1 + if 0 <= index < len(choices): + choice = choices[index] + + matched.append( + ModelResult( + start=match.start, + end=match.end, + type_name="choice", + text=match.text, + resolution=FoundChoice( + value=choice.value, index=index, score=1.0 + ), + ) + ) + except: + # noop here, as in dotnet/node repos + pass + + @staticmethod + def _recognize_number(utterance: str, culture: str) -> List[ModelResult]: + model: NumberModel = NumberRecognizer(culture).get_number_model(culture) + + return list( + map(ChoiceRecognizers._found_choice_constructor, model.parse(utterance)) + ) + + @staticmethod + def _found_choice_constructor(value_model: ModelResult) -> ModelResult: + return ModelResult( + start=value_model.start, + end=value_model.end, + type_name="choice", + text=value_model.text, + resolution=FoundChoice( + value=value_model.resolution["value"], index=0, score=1.0 + ), + ) diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_choices_options.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_choices_options.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_choices_options.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/find_choices_options.py @@ -1,23 +1,38 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -from .find_values_options import FindValuesOptions - - -class FindChoicesOptions(FindValuesOptions): - """ Contains options to control how input is matched against a list of choices """ - - def __init__(self, no_value: bool = None, no_action: bool = None, **kwargs): - """ - Parameters: - ----------- - - no_value: (Optional) If `True`, the choices `value` field will NOT be search over. Defaults to `False`. - - no_action: (Optional) If `True`, the choices `action.title` field will NOT be searched over. - Defaults to `False`. - """ - - super().__init__(**kwargs) - self.no_value = no_value - self.no_action = no_action +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from .find_values_options import FindValuesOptions + + +class FindChoicesOptions(FindValuesOptions): + """ Contains options to control how input is matched against a list of choices """ + + def __init__( + self, + no_value: bool = None, + no_action: bool = None, + recognize_numbers: bool = True, + recognize_ordinals: bool = True, + **kwargs, + ): + """ + Parameters: + ----------- + + no_value: (Optional) If `True`, the choices `value` field will NOT be search over. Defaults to `False`. + + no_action: (Optional) If `True`, the choices `action.title` field will NOT be searched over. + Defaults to `False`. + + recognize_numbers: (Optional) Indicates whether the recognizer should check for Numbers using the + NumberRecognizer's NumberModel. + + recognize_ordinals: (Options) Indicates whether the recognizer should check for Ordinal Numbers using + the NumberRecognizer's OrdinalModel. + """ + + super().__init__(**kwargs) + self.no_value = no_value + self.no_action = no_action + self.recognize_numbers = recognize_numbers + self.recognize_ordinals = recognize_ordinals
diff --git a/libraries/botbuilder-dialogs/tests/test_choice_prompt.py b/libraries/botbuilder-dialogs/tests/test_choice_prompt.py --- a/libraries/botbuilder-dialogs/tests/test_choice_prompt.py +++ b/libraries/botbuilder-dialogs/tests/test_choice_prompt.py @@ -1,695 +1,717 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -from typing import List - -import aiounittest -from recognizers_text import Culture - -from botbuilder.core import CardFactory, ConversationState, MemoryStorage, TurnContext -from botbuilder.core.adapters import TestAdapter -from botbuilder.dialogs import DialogSet, DialogTurnResult, DialogTurnStatus -from botbuilder.dialogs.choices import Choice, ListStyle -from botbuilder.dialogs.prompts import ( - ChoicePrompt, - PromptOptions, - PromptValidatorContext, -) -from botbuilder.schema import Activity, ActivityTypes - -_color_choices: List[Choice] = [ - Choice(value="red"), - Choice(value="green"), - Choice(value="blue"), -] - -_answer_message: Activity = Activity(text="red", type=ActivityTypes.message) -_invalid_message: Activity = Activity(text="purple", type=ActivityTypes.message) - - -class ChoicePromptTest(aiounittest.AsyncTestCase): - def test_choice_prompt_with_empty_id_should_fail(self): - empty_id = "" - - with self.assertRaises(TypeError): - ChoicePrompt(empty_id) - - def test_choice_prompt_with_none_id_should_fail(self): - none_id = None - - with self.assertRaises(TypeError): - ChoicePrompt(none_id) - - async def test_should_call_choice_prompt_using_dc_prompt(self): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - choices=_color_choices, - ) - await dialog_context.prompt("ChoicePrompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - # Initialize TestAdapter. - adapter = TestAdapter(exec_test) - - # Create new ConversationState with MemoryStorage and register the state as middleware. - convo_state = ConversationState(MemoryStorage()) - - # Create a DialogState property, DialogSet, and ChoicePrompt. - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - choice_prompt = ChoicePrompt("ChoicePrompt") - dialogs.add(choice_prompt) - - step1 = await adapter.send("hello") - step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" - ) - step3 = await step2.send(_answer_message) - await step3.assert_reply("red") - - async def test_should_call_choice_prompt_with_custom_validator(self): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - choices=_color_choices, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - async def validator(prompt: PromptValidatorContext) -> bool: - assert prompt - - return prompt.recognized.succeeded - - choice_prompt = ChoicePrompt("prompt", validator) - - dialogs.add(choice_prompt) - - step1 = await adapter.send("Hello") - step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" - ) - step3 = await step2.send(_invalid_message) - step4 = await step3.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" - ) - step5 = await step4.send(_answer_message) - await step5.assert_reply("red") - - async def test_should_send_custom_retry_prompt(self): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - retry_prompt=Activity( - type=ActivityTypes.message, - text="Please choose red, blue, or green.", - ), - choices=_color_choices, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - choice_prompt = ChoicePrompt("prompt") - dialogs.add(choice_prompt) - - step1 = await adapter.send("Hello") - step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" - ) - step3 = await step2.send(_invalid_message) - step4 = await step3.assert_reply( - "Please choose red, blue, or green. (1) red, (2) green, or (3) blue" - ) - step5 = await step4.send(_answer_message) - await step5.assert_reply("red") - - async def test_should_send_ignore_retry_prompt_if_validator_replies(self): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - retry_prompt=Activity( - type=ActivityTypes.message, - text="Please choose red, blue, or green.", - ), - choices=_color_choices, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - async def validator(prompt: PromptValidatorContext) -> bool: - assert prompt - - if not prompt.recognized.succeeded: - await prompt.context.send_activity("Bad input.") - - return prompt.recognized.succeeded - - choice_prompt = ChoicePrompt("prompt", validator) - - dialogs.add(choice_prompt) - - step1 = await adapter.send("Hello") - step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" - ) - step3 = await step2.send(_invalid_message) - step4 = await step3.assert_reply("Bad input.") - step5 = await step4.send(_answer_message) - await step5.assert_reply("red") - - async def test_should_use_default_locale_when_rendering_choices(self): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - choices=_color_choices, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - async def validator(prompt: PromptValidatorContext) -> bool: - assert prompt - - if not prompt.recognized.succeeded: - await prompt.context.send_activity("Bad input.") - - return prompt.recognized.succeeded - - choice_prompt = ChoicePrompt( - "prompt", validator, default_locale=Culture.Spanish - ) - - dialogs.add(choice_prompt) - - step1 = await adapter.send(Activity(type=ActivityTypes.message, text="Hello")) - step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, o (3) blue" - ) - step3 = await step2.send(_invalid_message) - step4 = await step3.assert_reply("Bad input.") - step5 = await step4.send(Activity(type=ActivityTypes.message, text="red")) - await step5.assert_reply("red") - - async def test_should_use_context_activity_locale_when_rendering_choices(self): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - choices=_color_choices, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - async def validator(prompt: PromptValidatorContext) -> bool: - assert prompt - - if not prompt.recognized.succeeded: - await prompt.context.send_activity("Bad input.") - - return prompt.recognized.succeeded - - choice_prompt = ChoicePrompt("prompt", validator) - dialogs.add(choice_prompt) - - step1 = await adapter.send( - Activity(type=ActivityTypes.message, text="Hello", locale=Culture.Spanish) - ) - step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, o (3) blue" - ) - step3 = await step2.send(_answer_message) - await step3.assert_reply("red") - - async def test_should_use_context_activity_locale_over_default_locale_when_rendering_choices( - self, - ): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - choices=_color_choices, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - async def validator(prompt: PromptValidatorContext) -> bool: - assert prompt - - if not prompt.recognized.succeeded: - await prompt.context.send_activity("Bad input.") - - return prompt.recognized.succeeded - - choice_prompt = ChoicePrompt( - "prompt", validator, default_locale=Culture.Spanish - ) - dialogs.add(choice_prompt) - - step1 = await adapter.send( - Activity(type=ActivityTypes.message, text="Hello", locale=Culture.English) - ) - step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" - ) - step3 = await step2.send(_answer_message) - await step3.assert_reply("red") - - async def test_should_not_render_choices_if_list_style_none_is_specified(self): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - choices=_color_choices, - style=ListStyle.none, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - choice_prompt = ChoicePrompt("prompt") - - dialogs.add(choice_prompt) - - step1 = await adapter.send("Hello") - step2 = await step1.assert_reply("Please choose a color.") - step3 = await step2.send(_answer_message) - await step3.assert_reply("red") - - async def test_should_create_prompt_with_inline_choices_when_specified(self): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - choices=_color_choices, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - choice_prompt = ChoicePrompt("prompt") - choice_prompt.style = ListStyle.in_line - - dialogs.add(choice_prompt) - - step1 = await adapter.send("Hello") - step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" - ) - step3 = await step2.send(_answer_message) - await step3.assert_reply("red") - - async def test_should_create_prompt_with_list_choices_when_specified(self): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - choices=_color_choices, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - choice_prompt = ChoicePrompt("prompt") - choice_prompt.style = ListStyle.list_style - - dialogs.add(choice_prompt) - - step1 = await adapter.send("Hello") - step2 = await step1.assert_reply( - "Please choose a color.\n\n 1. red\n 2. green\n 3. blue" - ) - step3 = await step2.send(_answer_message) - await step3.assert_reply("red") - - async def test_should_create_prompt_with_suggested_action_style_when_specified( - self, - ): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - choices=_color_choices, - style=ListStyle.suggested_action, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - choice_prompt = ChoicePrompt("prompt") - - dialogs.add(choice_prompt) - - step1 = await adapter.send("Hello") - step2 = await step1.assert_reply("Please choose a color.") - step3 = await step2.send(_answer_message) - await step3.assert_reply("red") - - async def test_should_create_prompt_with_auto_style_when_specified(self): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - choices=_color_choices, - style=ListStyle.auto, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - choice_prompt = ChoicePrompt("prompt") - - dialogs.add(choice_prompt) - - step1 = await adapter.send("Hello") - step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" - ) - step3 = await step2.send(_answer_message) - await step3.assert_reply("red") - - async def test_should_recognize_valid_number_choice(self): - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a color." - ), - choices=_color_choices, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - choice_prompt = ChoicePrompt("prompt") - - dialogs.add(choice_prompt) - - step1 = await adapter.send("Hello") - step2 = await step1.assert_reply( - "Please choose a color. (1) red, (2) green, or (3) blue" - ) - step3 = await step2.send("1") - await step3.assert_reply("red") - - async def test_should_display_choices_on_hero_card(self): - size_choices = ["large", "medium", "small"] - - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions( - prompt=Activity( - type=ActivityTypes.message, text="Please choose a size." - ), - choices=size_choices, - ) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - def assert_expected_activity( - activity: Activity, description - ): # pylint: disable=unused-argument - assert len(activity.attachments) == 1 - assert ( - activity.attachments[0].content_type - == CardFactory.content_types.hero_card - ) - assert activity.attachments[0].content.text == "Please choose a size." - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - choice_prompt = ChoicePrompt("prompt") - - # Change the ListStyle of the prompt to ListStyle.none. - choice_prompt.style = ListStyle.hero_card - - dialogs.add(choice_prompt) - - step1 = await adapter.send("Hello") - step2 = await step1.assert_reply(assert_expected_activity) - step3 = await step2.send("1") - await step3.assert_reply(size_choices[0]) - - async def test_should_display_choices_on_hero_card_with_additional_attachment(self): - size_choices = ["large", "medium", "small"] - card = CardFactory.adaptive_card( - { - "type": "AdaptiveCard", - "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", - "version": "1.2", - "body": [], - } - ) - card_activity = Activity(attachments=[card]) - - async def exec_test(turn_context: TurnContext): - dialog_context = await dialogs.create_context(turn_context) - - results: DialogTurnResult = await dialog_context.continue_dialog() - - if results.status == DialogTurnStatus.Empty: - options = PromptOptions(prompt=card_activity, choices=size_choices) - await dialog_context.prompt("prompt", options) - elif results.status == DialogTurnStatus.Complete: - selected_choice = results.result - await turn_context.send_activity(selected_choice.value) - - await convo_state.save_changes(turn_context) - - def assert_expected_activity( - activity: Activity, description - ): # pylint: disable=unused-argument - assert len(activity.attachments) == 2 - assert ( - activity.attachments[0].content_type - == CardFactory.content_types.adaptive_card - ) - assert ( - activity.attachments[1].content_type - == CardFactory.content_types.hero_card - ) - - adapter = TestAdapter(exec_test) - - convo_state = ConversationState(MemoryStorage()) - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - choice_prompt = ChoicePrompt("prompt") - - # Change the ListStyle of the prompt to ListStyle.none. - choice_prompt.style = ListStyle.hero_card - - dialogs.add(choice_prompt) - - step1 = await adapter.send("Hello") - await step1.assert_reply(assert_expected_activity) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from typing import List + +import aiounittest +from recognizers_text import Culture + +from botbuilder.core import CardFactory, ConversationState, MemoryStorage, TurnContext +from botbuilder.core.adapters import TestAdapter +from botbuilder.dialogs import ( + DialogSet, + DialogTurnResult, + DialogTurnStatus, + ChoiceRecognizers, + FindChoicesOptions, +) +from botbuilder.dialogs.choices import Choice, ListStyle +from botbuilder.dialogs.prompts import ( + ChoicePrompt, + PromptOptions, + PromptValidatorContext, +) +from botbuilder.schema import Activity, ActivityTypes + +_color_choices: List[Choice] = [ + Choice(value="red"), + Choice(value="green"), + Choice(value="blue"), +] + +_answer_message: Activity = Activity(text="red", type=ActivityTypes.message) +_invalid_message: Activity = Activity(text="purple", type=ActivityTypes.message) + + +class ChoicePromptTest(aiounittest.AsyncTestCase): + def test_choice_prompt_with_empty_id_should_fail(self): + empty_id = "" + + with self.assertRaises(TypeError): + ChoicePrompt(empty_id) + + def test_choice_prompt_with_none_id_should_fail(self): + none_id = None + + with self.assertRaises(TypeError): + ChoicePrompt(none_id) + + async def test_should_call_choice_prompt_using_dc_prompt(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + ) + await dialog_context.prompt("ChoicePrompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + # Initialize TestAdapter. + adapter = TestAdapter(exec_test) + + # Create new ConversationState with MemoryStorage and register the state as middleware. + convo_state = ConversationState(MemoryStorage()) + + # Create a DialogState property, DialogSet, and ChoicePrompt. + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + choice_prompt = ChoicePrompt("ChoicePrompt") + dialogs.add(choice_prompt) + + step1 = await adapter.send("hello") + step2 = await step1.assert_reply( + "Please choose a color. (1) red, (2) green, or (3) blue" + ) + step3 = await step2.send(_answer_message) + await step3.assert_reply("red") + + async def test_should_call_choice_prompt_with_custom_validator(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + async def validator(prompt: PromptValidatorContext) -> bool: + assert prompt + + return prompt.recognized.succeeded + + choice_prompt = ChoicePrompt("prompt", validator) + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply( + "Please choose a color. (1) red, (2) green, or (3) blue" + ) + step3 = await step2.send(_invalid_message) + step4 = await step3.assert_reply( + "Please choose a color. (1) red, (2) green, or (3) blue" + ) + step5 = await step4.send(_answer_message) + await step5.assert_reply("red") + + async def test_should_send_custom_retry_prompt(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + retry_prompt=Activity( + type=ActivityTypes.message, + text="Please choose red, blue, or green.", + ), + choices=_color_choices, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + choice_prompt = ChoicePrompt("prompt") + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply( + "Please choose a color. (1) red, (2) green, or (3) blue" + ) + step3 = await step2.send(_invalid_message) + step4 = await step3.assert_reply( + "Please choose red, blue, or green. (1) red, (2) green, or (3) blue" + ) + step5 = await step4.send(_answer_message) + await step5.assert_reply("red") + + async def test_should_send_ignore_retry_prompt_if_validator_replies(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + retry_prompt=Activity( + type=ActivityTypes.message, + text="Please choose red, blue, or green.", + ), + choices=_color_choices, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + async def validator(prompt: PromptValidatorContext) -> bool: + assert prompt + + if not prompt.recognized.succeeded: + await prompt.context.send_activity("Bad input.") + + return prompt.recognized.succeeded + + choice_prompt = ChoicePrompt("prompt", validator) + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply( + "Please choose a color. (1) red, (2) green, or (3) blue" + ) + step3 = await step2.send(_invalid_message) + step4 = await step3.assert_reply("Bad input.") + step5 = await step4.send(_answer_message) + await step5.assert_reply("red") + + async def test_should_use_default_locale_when_rendering_choices(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + async def validator(prompt: PromptValidatorContext) -> bool: + assert prompt + + if not prompt.recognized.succeeded: + await prompt.context.send_activity("Bad input.") + + return prompt.recognized.succeeded + + choice_prompt = ChoicePrompt( + "prompt", validator, default_locale=Culture.Spanish + ) + + dialogs.add(choice_prompt) + + step1 = await adapter.send(Activity(type=ActivityTypes.message, text="Hello")) + step2 = await step1.assert_reply( + "Please choose a color. (1) red, (2) green, o (3) blue" + ) + step3 = await step2.send(_invalid_message) + step4 = await step3.assert_reply("Bad input.") + step5 = await step4.send(Activity(type=ActivityTypes.message, text="red")) + await step5.assert_reply("red") + + async def test_should_use_context_activity_locale_when_rendering_choices(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + async def validator(prompt: PromptValidatorContext) -> bool: + assert prompt + + if not prompt.recognized.succeeded: + await prompt.context.send_activity("Bad input.") + + return prompt.recognized.succeeded + + choice_prompt = ChoicePrompt("prompt", validator) + dialogs.add(choice_prompt) + + step1 = await adapter.send( + Activity(type=ActivityTypes.message, text="Hello", locale=Culture.Spanish) + ) + step2 = await step1.assert_reply( + "Please choose a color. (1) red, (2) green, o (3) blue" + ) + step3 = await step2.send(_answer_message) + await step3.assert_reply("red") + + async def test_should_use_context_activity_locale_over_default_locale_when_rendering_choices( + self, + ): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + async def validator(prompt: PromptValidatorContext) -> bool: + assert prompt + + if not prompt.recognized.succeeded: + await prompt.context.send_activity("Bad input.") + + return prompt.recognized.succeeded + + choice_prompt = ChoicePrompt( + "prompt", validator, default_locale=Culture.Spanish + ) + dialogs.add(choice_prompt) + + step1 = await adapter.send( + Activity(type=ActivityTypes.message, text="Hello", locale=Culture.English) + ) + step2 = await step1.assert_reply( + "Please choose a color. (1) red, (2) green, or (3) blue" + ) + step3 = await step2.send(_answer_message) + await step3.assert_reply("red") + + async def test_should_not_render_choices_if_list_style_none_is_specified(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + style=ListStyle.none, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + choice_prompt = ChoicePrompt("prompt") + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply("Please choose a color.") + step3 = await step2.send(_answer_message) + await step3.assert_reply("red") + + async def test_should_create_prompt_with_inline_choices_when_specified(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + choice_prompt = ChoicePrompt("prompt") + choice_prompt.style = ListStyle.in_line + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply( + "Please choose a color. (1) red, (2) green, or (3) blue" + ) + step3 = await step2.send(_answer_message) + await step3.assert_reply("red") + + async def test_should_create_prompt_with_list_choices_when_specified(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + choice_prompt = ChoicePrompt("prompt") + choice_prompt.style = ListStyle.list_style + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply( + "Please choose a color.\n\n 1. red\n 2. green\n 3. blue" + ) + step3 = await step2.send(_answer_message) + await step3.assert_reply("red") + + async def test_should_create_prompt_with_suggested_action_style_when_specified( + self, + ): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + style=ListStyle.suggested_action, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + choice_prompt = ChoicePrompt("prompt") + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply("Please choose a color.") + step3 = await step2.send(_answer_message) + await step3.assert_reply("red") + + async def test_should_create_prompt_with_auto_style_when_specified(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + style=ListStyle.auto, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + choice_prompt = ChoicePrompt("prompt") + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply( + "Please choose a color. (1) red, (2) green, or (3) blue" + ) + step3 = await step2.send(_answer_message) + await step3.assert_reply("red") + + async def test_should_recognize_valid_number_choice(self): + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a color." + ), + choices=_color_choices, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + choice_prompt = ChoicePrompt("prompt") + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply( + "Please choose a color. (1) red, (2) green, or (3) blue" + ) + step3 = await step2.send("1") + await step3.assert_reply("red") + + async def test_should_display_choices_on_hero_card(self): + size_choices = ["large", "medium", "small"] + + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions( + prompt=Activity( + type=ActivityTypes.message, text="Please choose a size." + ), + choices=size_choices, + ) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + def assert_expected_activity( + activity: Activity, description + ): # pylint: disable=unused-argument + assert len(activity.attachments) == 1 + assert ( + activity.attachments[0].content_type + == CardFactory.content_types.hero_card + ) + assert activity.attachments[0].content.text == "Please choose a size." + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + choice_prompt = ChoicePrompt("prompt") + + # Change the ListStyle of the prompt to ListStyle.none. + choice_prompt.style = ListStyle.hero_card + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + step2 = await step1.assert_reply(assert_expected_activity) + step3 = await step2.send("1") + await step3.assert_reply(size_choices[0]) + + async def test_should_display_choices_on_hero_card_with_additional_attachment(self): + size_choices = ["large", "medium", "small"] + card = CardFactory.adaptive_card( + { + "type": "AdaptiveCard", + "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", + "version": "1.2", + "body": [], + } + ) + card_activity = Activity(attachments=[card]) + + async def exec_test(turn_context: TurnContext): + dialog_context = await dialogs.create_context(turn_context) + + results: DialogTurnResult = await dialog_context.continue_dialog() + + if results.status == DialogTurnStatus.Empty: + options = PromptOptions(prompt=card_activity, choices=size_choices) + await dialog_context.prompt("prompt", options) + elif results.status == DialogTurnStatus.Complete: + selected_choice = results.result + await turn_context.send_activity(selected_choice.value) + + await convo_state.save_changes(turn_context) + + def assert_expected_activity( + activity: Activity, description + ): # pylint: disable=unused-argument + assert len(activity.attachments) == 2 + assert ( + activity.attachments[0].content_type + == CardFactory.content_types.adaptive_card + ) + assert ( + activity.attachments[1].content_type + == CardFactory.content_types.hero_card + ) + + adapter = TestAdapter(exec_test) + + convo_state = ConversationState(MemoryStorage()) + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + choice_prompt = ChoicePrompt("prompt") + + # Change the ListStyle of the prompt to ListStyle.none. + choice_prompt.style = ListStyle.hero_card + + dialogs.add(choice_prompt) + + step1 = await adapter.send("Hello") + await step1.assert_reply(assert_expected_activity) + + async def test_should_not_find_a_choice_in_an_utterance_by_ordinal(self): + found = ChoiceRecognizers.recognize_choices( + "the first one please", + _color_choices, + FindChoicesOptions(recognize_numbers=False, recognize_ordinals=False), + ) + assert not found + + async def test_should_not_find_a_choice_in_an_utterance_by_numerical_index(self): + found = ChoiceRecognizers.recognize_choices( + "one", + _color_choices, + FindChoicesOptions(recognize_numbers=False, recognize_ordinals=False), + ) + assert not found
[PORT] Add RecognizeOrdinals and RecognizeNumbers flags to FindChoicesOptions > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3216 Fixes https://github.com/microsoft/botbuilder-dotnet/issues/2956 and https://github.com/microsoft/botbuilder-dotnet/issues/3039
2020-02-03T20:33:01
microsoft/botbuilder-python
738
microsoft__botbuilder-python-738
[ "534" ]
9fbc31858e249640763e2198f6f03bd683d5a895
diff --git a/libraries/botbuilder-core/botbuilder/core/teams/teams_helper.py b/libraries/botbuilder-core/botbuilder/core/teams/teams_helper.py --- a/libraries/botbuilder-core/botbuilder/core/teams/teams_helper.py +++ b/libraries/botbuilder-core/botbuilder/core/teams/teams_helper.py @@ -10,23 +10,21 @@ import botbuilder.schema as schema import botbuilder.schema.teams as teams_schema -# Optimization: The dependencies dictionary could be cached here, -# and shared between the two methods. +DEPENDICIES = [ + schema_cls + for key, schema_cls in getmembers(schema) + if isinstance(schema_cls, type) and issubclass(schema_cls, (Model, Enum)) +] +DEPENDICIES += [ + schema_cls + for key, schema_cls in getmembers(teams_schema) + if isinstance(schema_cls, type) and issubclass(schema_cls, (Model, Enum)) +] +DEPENDICIES_DICT = {dependency.__name__: dependency for dependency in DEPENDICIES} def deserializer_helper(msrest_cls: Type[Model], dict_to_deserialize: dict) -> Model: - dependencies = [ - schema_cls - for key, schema_cls in getmembers(schema) - if isinstance(schema_cls, type) and issubclass(schema_cls, (Model, Enum)) - ] - dependencies += [ - schema_cls - for key, schema_cls in getmembers(teams_schema) - if isinstance(schema_cls, type) and issubclass(schema_cls, (Model, Enum)) - ] - dependencies_dict = {dependency.__name__: dependency for dependency in dependencies} - deserializer = Deserializer(dependencies_dict) + deserializer = Deserializer(DEPENDICIES_DICT) return deserializer(msrest_cls.__name__, dict_to_deserialize) @@ -34,17 +32,6 @@ def serializer_helper(object_to_serialize: Model) -> dict: if object_to_serialize is None: return None - dependencies = [ - schema_cls - for key, schema_cls in getmembers(schema) - if isinstance(schema_cls, type) and issubclass(schema_cls, (Model, Enum)) - ] - dependencies += [ - schema_cls - for key, schema_cls in getmembers(teams_schema) - if isinstance(schema_cls, type) and issubclass(schema_cls, (Model, Enum)) - ] - dependencies_dict = {dependency.__name__: dependency for dependency in dependencies} - serializer = Serializer(dependencies_dict) + serializer = Serializer(DEPENDICIES_DICT) # pylint: disable=protected-access return serializer._serialize(object_to_serialize)
Consolidate serialization helpers to be static and shared In the teams_helper there are 2 serialization helper methods. Currently they both create a big dict of all the Model objects that exist in Teams and BF. We should make the optimization to make the big dict once, and update the 2 helpers to use the new dict.
@virtual-josh, please drive to closure. Add better description.
2020-02-13T01:58:54
microsoft/botbuilder-python
741
microsoft__botbuilder-python-741
[ "740" ]
44ab9aec81be7d370291cb4a7594aad844a332ec
diff --git a/libraries/botbuilder-integration-applicationinsights-aiohttp/setup.py b/libraries/botbuilder-integration-applicationinsights-aiohttp/setup.py --- a/libraries/botbuilder-integration-applicationinsights-aiohttp/setup.py +++ b/libraries/botbuilder-integration-applicationinsights-aiohttp/setup.py @@ -6,14 +6,14 @@ REQUIRES = [ "applicationinsights>=0.11.9", - "botbuilder-schema>=4.4.0b1", - "botframework-connector>=4.4.0b1", - "botbuilder-core>=4.4.0b1", - "botbuilder-applicationinsights>=4.4.0b1", + "aiohttp==3.6.2", + "botbuilder-schema>=4.7.1", + "botframework-connector>=4.7.1", + "botbuilder-core>=4.7.1", + "botbuilder-applicationinsights>=4.7.1", ] TESTS_REQUIRES = [ "aiounittest==1.3.0", - "aiohttp==3.5.4", ] root = os.path.abspath(os.path.dirname(__file__))
Fix versioning on dependencies Fix dependency package versions to be consistent with the rest of the libraries
2020-02-13T23:55:55
microsoft/botbuilder-python
744
microsoft__botbuilder-python-744
[ "684" ]
44af3b81efb9af88459cea06c8974ebba68dc9f1
diff --git a/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py b/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py --- a/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py +++ b/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py @@ -1,95 +1,95 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -import time -from functools import wraps -from typing import Awaitable, Callable - -from botbuilder.schema import Activity, ActivityTypes - -from .middleware_set import Middleware -from .turn_context import TurnContext - - -def delay(span=0.0): - def wrap(func): - @wraps(func) - async def delayed(): - time.sleep(span) - await func() - - return delayed - - return wrap - - -class Timer: - clear_timer = False - - async def set_timeout(self, func, time): - is_invocation_cancelled = False - - @delay(time) - async def some_fn(): # pylint: disable=function-redefined - if not self.clear_timer: - await func() - - await some_fn() - return is_invocation_cancelled - - def set_clear_timer(self): - self.clear_timer = True - - -class ShowTypingMiddleware(Middleware): - def __init__(self, delay: float = 0.5, period: float = 2.0): - if delay < 0: - raise ValueError("Delay must be greater than or equal to zero") - - if period <= 0: - raise ValueError("Repeat period must be greater than zero") - - self._delay = delay - self._period = period - - async def on_turn( - self, context: TurnContext, logic: Callable[[TurnContext], Awaitable] - ): - finished = False - timer = Timer() - - async def start_interval(context: TurnContext, delay: int, period: int): - async def aux(): - if not finished: - typing_activity = Activity( - type=ActivityTypes.typing, - relates_to=context.activity.relates_to, - ) - - conversation_reference = TurnContext.get_conversation_reference( - context.activity - ) - - typing_activity = TurnContext.apply_conversation_reference( - typing_activity, conversation_reference - ) - - await context.adapter.send_activities(context, [typing_activity]) - - start_interval(context, period, period) - - await timer.set_timeout(aux, delay) - - def stop_interval(): - nonlocal finished - finished = True - timer.set_clear_timer() - - if context.activity.type == ActivityTypes.message: - finished = False - await start_interval(context, self._delay, self._period) - - result = await logic() - stop_interval() - - return result +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import time +from functools import wraps +from typing import Awaitable, Callable + +from botbuilder.schema import Activity, ActivityTypes + +from .middleware_set import Middleware +from .turn_context import TurnContext + + +def delay(span=0.0): + def wrap(func): + @wraps(func) + async def delayed(): + time.sleep(span) + await func() + + return delayed + + return wrap + + +class Timer: + clear_timer = False + + async def set_timeout(self, func, time): + is_invocation_cancelled = False + + @delay(time) + async def some_fn(): # pylint: disable=function-redefined + if not self.clear_timer: + await func() + + await some_fn() + return is_invocation_cancelled + + def set_clear_timer(self): + self.clear_timer = True + + +class ShowTypingMiddleware(Middleware): + def __init__(self, delay: float = 0.5, period: float = 2.0): + if delay < 0: + raise ValueError("Delay must be greater than or equal to zero") + + if period <= 0: + raise ValueError("Repeat period must be greater than zero") + + self._delay = delay + self._period = period + + async def on_turn( + self, context: TurnContext, logic: Callable[[TurnContext], Awaitable] + ): + finished = False + timer = Timer() + + async def start_interval(context: TurnContext, delay: int, period: int): + async def aux(): + if not finished: + typing_activity = Activity( + type=ActivityTypes.typing, + relates_to=context.activity.relates_to, + ) + + conversation_reference = TurnContext.get_conversation_reference( + context.activity + ) + + typing_activity = TurnContext.apply_conversation_reference( + typing_activity, conversation_reference + ) + + await context.adapter.send_activities(context, [typing_activity]) + + start_interval(context, period, period) + + await timer.set_timeout(aux, delay) + + def stop_interval(): + nonlocal finished + finished = True + timer.set_clear_timer() + + if context.activity.type == ActivityTypes.message: + finished = False + await start_interval(context, self._delay, self._period) + + result = await logic() + stop_interval() + + return result diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py @@ -59,7 +59,7 @@ async def begin_dialog( properties = {} properties["DialogId"] = self.id properties["InstanceId"] = instance_id - self.telemetry_client.track_event("WaterfallStart", properties=properties) + self.telemetry_client.track_event("WaterfallStart", properties) # Run first stepkinds return await self.run_step(dialog_context, 0, DialogReason.BeginCalled, None)
diff --git a/libraries/botbuilder-ai/tests/qna/test_qna.py b/libraries/botbuilder-ai/tests/qna/test_qna.py --- a/libraries/botbuilder-ai/tests/qna/test_qna.py +++ b/libraries/botbuilder-ai/tests/qna/test_qna.py @@ -1,963 +1,965 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -# pylint: disable=protected-access - -import json -from os import path -from typing import List, Dict -import unittest -from unittest.mock import patch -from aiohttp import ClientSession - -import aiounittest -from botbuilder.ai.qna import QnAMakerEndpoint, QnAMaker, QnAMakerOptions -from botbuilder.ai.qna.models import ( - FeedbackRecord, - Metadata, - QueryResult, - QnARequestContext, -) -from botbuilder.ai.qna.utils import QnATelemetryConstants -from botbuilder.core import BotAdapter, BotTelemetryClient, TurnContext -from botbuilder.core.adapters import TestAdapter -from botbuilder.schema import ( - Activity, - ActivityTypes, - ChannelAccount, - ConversationAccount, -) - - -class TestContext(TurnContext): - def __init__(self, request): - super().__init__(TestAdapter(), request) - self.sent: List[Activity] = list() - - self.on_send_activities(self.capture_sent_activities) - - async def capture_sent_activities( - self, context: TurnContext, activities, next - ): # pylint: disable=unused-argument - self.sent += activities - context.responded = True - - -class QnaApplicationTest(aiounittest.AsyncTestCase): - # Note this is NOT a real QnA Maker application ID nor a real QnA Maker subscription-key - # theses are GUIDs edited to look right to the parsing and validation code. - - _knowledge_base_id: str = "f028d9k3-7g9z-11d3-d300-2b8x98227q8w" - _endpoint_key: str = "1k997n7w-207z-36p3-j2u1-09tas20ci6011" - _host: str = "https://dummyqnahost.azurewebsites.net/qnamaker" - - tests_endpoint = QnAMakerEndpoint(_knowledge_base_id, _endpoint_key, _host) - - def test_qnamaker_construction(self): - # Arrange - endpoint = self.tests_endpoint - - # Act - qna = QnAMaker(endpoint) - endpoint = qna._endpoint - - # Assert - self.assertEqual( - "f028d9k3-7g9z-11d3-d300-2b8x98227q8w", endpoint.knowledge_base_id - ) - self.assertEqual("1k997n7w-207z-36p3-j2u1-09tas20ci6011", endpoint.endpoint_key) - self.assertEqual( - "https://dummyqnahost.azurewebsites.net/qnamaker", endpoint.host - ) - - def test_endpoint_with_empty_kbid(self): - empty_kbid = "" - - with self.assertRaises(TypeError): - QnAMakerEndpoint(empty_kbid, self._endpoint_key, self._host) - - def test_endpoint_with_empty_endpoint_key(self): - empty_endpoint_key = "" - - with self.assertRaises(TypeError): - QnAMakerEndpoint(self._knowledge_base_id, empty_endpoint_key, self._host) - - def test_endpoint_with_emptyhost(self): - with self.assertRaises(TypeError): - QnAMakerEndpoint(self._knowledge_base_id, self._endpoint_key, "") - - def test_qnamaker_with_none_endpoint(self): - with self.assertRaises(TypeError): - QnAMaker(None) - - def test_set_default_options_with_no_options_arg(self): - qna_without_options = QnAMaker(self.tests_endpoint) - options = qna_without_options._generate_answer_helper.options - - default_threshold = 0.3 - default_top = 1 - default_strict_filters = [] - - self.assertEqual(default_threshold, options.score_threshold) - self.assertEqual(default_top, options.top) - self.assertEqual(default_strict_filters, options.strict_filters) - - def test_options_passed_to_ctor(self): - options = QnAMakerOptions( - score_threshold=0.8, - timeout=9000, - top=5, - strict_filters=[Metadata("movie", "disney")], - ) - - qna_with_options = QnAMaker(self.tests_endpoint, options) - actual_options = qna_with_options._generate_answer_helper.options - - expected_threshold = 0.8 - expected_timeout = 9000 - expected_top = 5 - expected_strict_filters = [Metadata("movie", "disney")] - - self.assertEqual(expected_threshold, actual_options.score_threshold) - self.assertEqual(expected_timeout, actual_options.timeout) - self.assertEqual(expected_top, actual_options.top) - self.assertEqual( - expected_strict_filters[0].name, actual_options.strict_filters[0].name - ) - self.assertEqual( - expected_strict_filters[0].value, actual_options.strict_filters[0].value - ) - - async def test_returns_answer(self): - # Arrange - question: str = "how do I clean the stove?" - response_path: str = "ReturnsAnswer.json" - - # Act - result = await QnaApplicationTest._get_service_result(question, response_path) - - first_answer = result[0] - - # Assert - self.assertIsNotNone(result) - self.assertEqual(1, len(result)) - self.assertEqual( - "BaseCamp: You can use a damp rag to clean around the Power Pack", - first_answer.answer, - ) - - async def test_active_learning_enabled_status(self): - # Arrange - question: str = "how do I clean the stove?" - response_path: str = "ReturnsAnswer.json" - - # Act - result = await QnaApplicationTest._get_service_result_raw( - question, response_path - ) - - # Assert - self.assertIsNotNone(result) - self.assertEqual(1, len(result.answers)) - self.assertFalse(result.active_learning_enabled) - - async def test_returns_answer_using_options(self): - # Arrange - question: str = "up" - response_path: str = "AnswerWithOptions.json" - options = QnAMakerOptions( - score_threshold=0.8, top=5, strict_filters=[Metadata("movie", "disney")] - ) - - # Act - result = await QnaApplicationTest._get_service_result( - question, response_path, options=options - ) - - first_answer = result[0] - has_at_least_1_ans = True - first_metadata = first_answer.metadata[0] - - # Assert - self.assertIsNotNone(result) - self.assertEqual(has_at_least_1_ans, len(result) >= 1) - self.assertTrue(first_answer.answer[0]) - self.assertEqual("is a movie", first_answer.answer) - self.assertTrue(first_answer.score >= options.score_threshold) - self.assertEqual("movie", first_metadata.name) - self.assertEqual("disney", first_metadata.value) - - async def test_trace_test(self): - activity = Activity( - type=ActivityTypes.message, - text="how do I clean the stove?", - conversation=ConversationAccount(), - recipient=ChannelAccount(), - from_property=ChannelAccount(), - ) - - response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") - qna = QnAMaker(QnaApplicationTest.tests_endpoint) - - context = TestContext(activity) - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - result = await qna.get_answers(context) - - qna_trace_activities = list( - filter( - lambda act: act.type == "trace" and act.name == "QnAMaker", - context.sent, - ) - ) - trace_activity = qna_trace_activities[0] - - self.assertEqual("trace", trace_activity.type) - self.assertEqual("QnAMaker", trace_activity.name) - self.assertEqual("QnAMaker Trace", trace_activity.label) - self.assertEqual( - "https://www.qnamaker.ai/schemas/trace", trace_activity.value_type - ) - self.assertEqual(True, hasattr(trace_activity, "value")) - self.assertEqual(True, hasattr(trace_activity.value, "message")) - self.assertEqual(True, hasattr(trace_activity.value, "query_results")) - self.assertEqual(True, hasattr(trace_activity.value, "score_threshold")) - self.assertEqual(True, hasattr(trace_activity.value, "top")) - self.assertEqual(True, hasattr(trace_activity.value, "strict_filters")) - self.assertEqual( - self._knowledge_base_id, trace_activity.value.knowledge_base_id - ) - - return result - - async def test_returns_answer_with_timeout(self): - question: str = "how do I clean the stove?" - options = QnAMakerOptions(timeout=999999) - qna = QnAMaker(QnaApplicationTest.tests_endpoint, options) - context = QnaApplicationTest._get_context(question, TestAdapter()) - response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - result = await qna.get_answers(context, options) - - self.assertIsNotNone(result) - self.assertEqual( - options.timeout, qna._generate_answer_helper.options.timeout - ) - - async def test_telemetry_returns_answer(self): - # Arrange - question: str = "how do I clean the stove?" - response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") - telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) - log_personal_information = True - context = QnaApplicationTest._get_context(question, TestAdapter()) - qna = QnAMaker( - QnaApplicationTest.tests_endpoint, - telemetry_client=telemetry_client, - log_personal_information=log_personal_information, - ) - - # Act - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers(context) - - telemetry_args = telemetry_client.track_event.call_args_list[0][1] - telemetry_properties = telemetry_args["properties"] - telemetry_metrics = telemetry_args["measurements"] - number_of_args = len(telemetry_args) - first_answer = telemetry_args["properties"][ - QnATelemetryConstants.answer_property - ] - expected_answer = ( - "BaseCamp: You can use a damp rag to clean around the Power Pack" - ) - - # Assert - Check Telemetry logged. - self.assertEqual(1, telemetry_client.track_event.call_count) - self.assertEqual(3, number_of_args) - self.assertEqual("QnaMessage", telemetry_args["name"]) - self.assertTrue("answer" in telemetry_properties) - self.assertTrue("knowledgeBaseId" in telemetry_properties) - self.assertTrue("matchedQuestion" in telemetry_properties) - self.assertTrue("question" in telemetry_properties) - self.assertTrue("questionId" in telemetry_properties) - self.assertTrue("articleFound" in telemetry_properties) - self.assertEqual(expected_answer, first_answer) - self.assertTrue("score" in telemetry_metrics) - self.assertEqual(1, telemetry_metrics["score"]) - - # Assert - Validate we didn't break QnA functionality. - self.assertIsNotNone(results) - self.assertEqual(1, len(results)) - self.assertEqual(expected_answer, results[0].answer) - self.assertEqual("Editorial", results[0].source) - - async def test_telemetry_returns_answer_when_no_answer_found_in_kb(self): - # Arrange - question: str = "gibberish question" - response_json = QnaApplicationTest._get_json_for_file("NoAnswerFoundInKb.json") - telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) - qna = QnAMaker( - QnaApplicationTest.tests_endpoint, - telemetry_client=telemetry_client, - log_personal_information=True, - ) - context = QnaApplicationTest._get_context(question, TestAdapter()) - - # Act - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers(context) - - telemetry_args = telemetry_client.track_event.call_args_list[0][1] - telemetry_properties = telemetry_args["properties"] - number_of_args = len(telemetry_args) - first_answer = telemetry_args["properties"][ - QnATelemetryConstants.answer_property - ] - expected_answer = "No Qna Answer matched" - expected_matched_question = "No Qna Question matched" - - # Assert - Check Telemetry logged. - self.assertEqual(1, telemetry_client.track_event.call_count) - self.assertEqual(3, number_of_args) - self.assertEqual("QnaMessage", telemetry_args["name"]) - self.assertTrue("answer" in telemetry_properties) - self.assertTrue("knowledgeBaseId" in telemetry_properties) - self.assertTrue("matchedQuestion" in telemetry_properties) - self.assertEqual( - expected_matched_question, - telemetry_properties[QnATelemetryConstants.matched_question_property], - ) - self.assertTrue("question" in telemetry_properties) - self.assertTrue("questionId" in telemetry_properties) - self.assertTrue("articleFound" in telemetry_properties) - self.assertEqual(expected_answer, first_answer) - - # Assert - Validate we didn't break QnA functionality. - self.assertIsNotNone(results) - self.assertEqual(0, len(results)) - - async def test_telemetry_pii(self): - # Arrange - question: str = "how do I clean the stove?" - response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") - telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) - log_personal_information = False - context = QnaApplicationTest._get_context(question, TestAdapter()) - qna = QnAMaker( - QnaApplicationTest.tests_endpoint, - telemetry_client=telemetry_client, - log_personal_information=log_personal_information, - ) - - # Act - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers(context) - - telemetry_args = telemetry_client.track_event.call_args_list[0][1] - telemetry_properties = telemetry_args["properties"] - telemetry_metrics = telemetry_args["measurements"] - number_of_args = len(telemetry_args) - first_answer = telemetry_args["properties"][ - QnATelemetryConstants.answer_property - ] - expected_answer = ( - "BaseCamp: You can use a damp rag to clean around the Power Pack" - ) - - # Assert - Validate PII properties not logged. - self.assertEqual(1, telemetry_client.track_event.call_count) - self.assertEqual(3, number_of_args) - self.assertEqual("QnaMessage", telemetry_args["name"]) - self.assertTrue("answer" in telemetry_properties) - self.assertTrue("knowledgeBaseId" in telemetry_properties) - self.assertTrue("matchedQuestion" in telemetry_properties) - self.assertTrue("question" not in telemetry_properties) - self.assertTrue("questionId" in telemetry_properties) - self.assertTrue("articleFound" in telemetry_properties) - self.assertEqual(expected_answer, first_answer) - self.assertTrue("score" in telemetry_metrics) - self.assertEqual(1, telemetry_metrics["score"]) - - # Assert - Validate we didn't break QnA functionality. - self.assertIsNotNone(results) - self.assertEqual(1, len(results)) - self.assertEqual(expected_answer, results[0].answer) - self.assertEqual("Editorial", results[0].source) - - async def test_telemetry_override(self): - # Arrange - question: str = "how do I clean the stove?" - response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") - context = QnaApplicationTest._get_context(question, TestAdapter()) - options = QnAMakerOptions(top=1) - telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) - log_personal_information = False - - # Act - Override the QnAMaker object to log custom stuff and honor params passed in. - telemetry_properties: Dict[str, str] = {"id": "MyId"} - qna = QnaApplicationTest.OverrideTelemetry( - QnaApplicationTest.tests_endpoint, - options, - None, - telemetry_client, - log_personal_information, - ) - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers(context, options, telemetry_properties) - - telemetry_args = telemetry_client.track_event.call_args_list - first_call_args = telemetry_args[0][0] - first_call_properties = first_call_args[1] - second_call_args = telemetry_args[1][0] - second_call_properties = second_call_args[1] - expected_answer = ( - "BaseCamp: You can use a damp rag to clean around the Power Pack" - ) - - # Assert - self.assertEqual(2, telemetry_client.track_event.call_count) - self.assertEqual(2, len(first_call_args)) - self.assertEqual("QnaMessage", first_call_args[0]) - self.assertEqual(2, len(first_call_properties)) - self.assertTrue("my_important_property" in first_call_properties) - self.assertEqual( - "my_important_value", first_call_properties["my_important_property"] - ) - self.assertTrue("id" in first_call_properties) - self.assertEqual("MyId", first_call_properties["id"]) - - self.assertEqual("my_second_event", second_call_args[0]) - self.assertTrue("my_important_property2" in second_call_properties) - self.assertEqual( - "my_important_value2", second_call_properties["my_important_property2"] - ) - - # Validate we didn't break QnA functionality. - self.assertIsNotNone(results) - self.assertEqual(1, len(results)) - self.assertEqual(expected_answer, results[0].answer) - self.assertEqual("Editorial", results[0].source) - - async def test_telemetry_additional_props_metrics(self): - # Arrange - question: str = "how do I clean the stove?" - response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") - context = QnaApplicationTest._get_context(question, TestAdapter()) - options = QnAMakerOptions(top=1) - telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) - log_personal_information = False - - # Act - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - qna = QnAMaker( - QnaApplicationTest.tests_endpoint, - options, - None, - telemetry_client, - log_personal_information, - ) - telemetry_properties: Dict[str, str] = { - "my_important_property": "my_important_value" - } - telemetry_metrics: Dict[str, float] = {"my_important_metric": 3.14159} - - results = await qna.get_answers( - context, None, telemetry_properties, telemetry_metrics - ) - - # Assert - Added properties were added. - telemetry_args = telemetry_client.track_event.call_args_list[0][1] - telemetry_properties = telemetry_args["properties"] - expected_answer = ( - "BaseCamp: You can use a damp rag to clean around the Power Pack" - ) - - self.assertEqual(1, telemetry_client.track_event.call_count) - self.assertEqual(3, len(telemetry_args)) - self.assertEqual("QnaMessage", telemetry_args["name"]) - self.assertTrue("knowledgeBaseId" in telemetry_properties) - self.assertTrue("question" not in telemetry_properties) - self.assertTrue("matchedQuestion" in telemetry_properties) - self.assertTrue("questionId" in telemetry_properties) - self.assertTrue("answer" in telemetry_properties) - self.assertTrue(expected_answer, telemetry_properties["answer"]) - self.assertTrue("my_important_property" in telemetry_properties) - self.assertEqual( - "my_important_value", telemetry_properties["my_important_property"] - ) - - tracked_metrics = telemetry_args["measurements"] - - self.assertEqual(2, len(tracked_metrics)) - self.assertTrue("score" in tracked_metrics) - self.assertTrue("my_important_metric" in tracked_metrics) - self.assertEqual(3.14159, tracked_metrics["my_important_metric"]) - - # Assert - Validate we didn't break QnA functionality. - self.assertIsNotNone(results) - self.assertEqual(1, len(results)) - self.assertEqual(expected_answer, results[0].answer) - self.assertEqual("Editorial", results[0].source) - - async def test_telemetry_additional_props_override(self): - question: str = "how do I clean the stove?" - response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") - context = QnaApplicationTest._get_context(question, TestAdapter()) - options = QnAMakerOptions(top=1) - telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) - log_personal_information = False - - # Act - Pass in properties during QnA invocation that override default properties - # NOTE: We are invoking this with PII turned OFF, and passing a PII property (originalQuestion). - qna = QnAMaker( - QnaApplicationTest.tests_endpoint, - options, - None, - telemetry_client, - log_personal_information, - ) - telemetry_properties = { - "knowledge_base_id": "my_important_value", - "original_question": "my_important_value2", - } - telemetry_metrics = {"score": 3.14159} - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers( - context, None, telemetry_properties, telemetry_metrics - ) - - # Assert - Added properties were added. - tracked_args = telemetry_client.track_event.call_args_list[0][1] - tracked_properties = tracked_args["properties"] - expected_answer = ( - "BaseCamp: You can use a damp rag to clean around the Power Pack" - ) - tracked_metrics = tracked_args["measurements"] - - self.assertEqual(1, telemetry_client.track_event.call_count) - self.assertEqual(3, len(tracked_args)) - self.assertEqual("QnaMessage", tracked_args["name"]) - self.assertTrue("knowledge_base_id" in tracked_properties) - self.assertEqual( - "my_important_value", tracked_properties["knowledge_base_id"] - ) - self.assertTrue("original_question" in tracked_properties) - self.assertTrue("matchedQuestion" in tracked_properties) - self.assertEqual( - "my_important_value2", tracked_properties["original_question"] - ) - self.assertTrue("question" not in tracked_properties) - self.assertTrue("questionId" in tracked_properties) - self.assertTrue("answer" in tracked_properties) - self.assertEqual(expected_answer, tracked_properties["answer"]) - self.assertTrue("my_important_property" not in tracked_properties) - self.assertEqual(1, len(tracked_metrics)) - self.assertTrue("score" in tracked_metrics) - self.assertEqual(3.14159, tracked_metrics["score"]) - - # Assert - Validate we didn't break QnA functionality. - self.assertIsNotNone(results) - self.assertEqual(1, len(results)) - self.assertEqual(expected_answer, results[0].answer) - self.assertEqual("Editorial", results[0].source) - - async def test_telemetry_fill_props_override(self): - # Arrange - question: str = "how do I clean the stove?" - response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") - context: TurnContext = QnaApplicationTest._get_context(question, TestAdapter()) - options = QnAMakerOptions(top=1) - telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) - log_personal_information = False - - # Act - Pass in properties during QnA invocation that override default properties - # In addition Override with derivation. This presents an interesting question of order of setting - # properties. - # If I want to override "originalQuestion" property: - # - Set in "Stock" schema - # - Set in derived QnAMaker class - # - Set in GetAnswersAsync - # Logically, the GetAnswersAync should win. But ultimately OnQnaResultsAsync decides since it is the last - # code to touch the properties before logging (since it actually logs the event). - qna = QnaApplicationTest.OverrideFillTelemetry( - QnaApplicationTest.tests_endpoint, - options, - None, - telemetry_client, - log_personal_information, - ) - telemetry_properties: Dict[str, str] = { - "knowledgeBaseId": "my_important_value", - "matchedQuestion": "my_important_value2", - } - telemetry_metrics: Dict[str, float] = {"score": 3.14159} - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers( - context, None, telemetry_properties, telemetry_metrics - ) - - # Assert - Added properties were added. - first_call_args = telemetry_client.track_event.call_args_list[0][0] - first_properties = first_call_args[1] - expected_answer = ( - "BaseCamp: You can use a damp rag to clean around the Power Pack" - ) - first_metrics = first_call_args[2] - - self.assertEqual(2, telemetry_client.track_event.call_count) - self.assertEqual(3, len(first_call_args)) - self.assertEqual("QnaMessage", first_call_args[0]) - self.assertEqual(6, len(first_properties)) - self.assertTrue("knowledgeBaseId" in first_properties) - self.assertEqual("my_important_value", first_properties["knowledgeBaseId"]) - self.assertTrue("matchedQuestion" in first_properties) - self.assertEqual("my_important_value2", first_properties["matchedQuestion"]) - self.assertTrue("questionId" in first_properties) - self.assertTrue("answer" in first_properties) - self.assertEqual(expected_answer, first_properties["answer"]) - self.assertTrue("articleFound" in first_properties) - self.assertTrue("my_important_property" in first_properties) - self.assertEqual( - "my_important_value", first_properties["my_important_property"] - ) - - self.assertEqual(1, len(first_metrics)) - self.assertTrue("score" in first_metrics) - self.assertEqual(3.14159, first_metrics["score"]) - - # Assert - Validate we didn't break QnA functionality. - self.assertIsNotNone(results) - self.assertEqual(1, len(results)) - self.assertEqual(expected_answer, results[0].answer) - self.assertEqual("Editorial", results[0].source) - - async def test_call_train(self): - feedback_records = [] - - feedback1 = FeedbackRecord( - qna_id=1, user_id="test", user_question="How are you?" - ) - - feedback2 = FeedbackRecord(qna_id=2, user_id="test", user_question="What up??") - - feedback_records.extend([feedback1, feedback2]) - - with patch.object( - QnAMaker, "call_train", return_value=None - ) as mocked_call_train: - qna = QnAMaker(QnaApplicationTest.tests_endpoint) - qna.call_train(feedback_records) - - mocked_call_train.assert_called_once_with(feedback_records) - - async def test_should_filter_low_score_variation(self): - options = QnAMakerOptions(top=5) - qna = QnAMaker(QnaApplicationTest.tests_endpoint, options) - question: str = "Q11" - context = QnaApplicationTest._get_context(question, TestAdapter()) - response_json = QnaApplicationTest._get_json_for_file("TopNAnswer.json") - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers(context) - self.assertEqual(4, len(results), "Should have received 4 answers.") - - filtered_results = qna.get_low_score_variation(results) - self.assertEqual( - 3, - len(filtered_results), - "Should have 3 filtered answers after low score variation.", - ) - - async def test_should_answer_with_is_test_true(self): - options = QnAMakerOptions(top=1, is_test=True) - qna = QnAMaker(QnaApplicationTest.tests_endpoint) - question: str = "Q11" - context = QnaApplicationTest._get_context(question, TestAdapter()) - response_json = QnaApplicationTest._get_json_for_file( - "QnaMaker_IsTest_true.json" - ) - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers(context, options=options) - self.assertEqual(0, len(results), "Should have received zero answer.") - - async def test_should_answer_with_ranker_type_question_only(self): - options = QnAMakerOptions(top=1, ranker_type="QuestionOnly") - qna = QnAMaker(QnaApplicationTest.tests_endpoint) - question: str = "Q11" - context = QnaApplicationTest._get_context(question, TestAdapter()) - response_json = QnaApplicationTest._get_json_for_file( - "QnaMaker_RankerType_QuestionOnly.json" - ) - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers(context, options=options) - self.assertEqual(2, len(results), "Should have received two answers.") - - async def test_should_answer_with_prompts(self): - options = QnAMakerOptions(top=2) - qna = QnAMaker(QnaApplicationTest.tests_endpoint, options) - question: str = "how do I clean the stove?" - turn_context = QnaApplicationTest._get_context(question, TestAdapter()) - response_json = QnaApplicationTest._get_json_for_file("AnswerWithPrompts.json") - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers(turn_context, options) - self.assertEqual(1, len(results), "Should have received 1 answers.") - self.assertEqual( - 1, len(results[0].context.prompts), "Should have received 1 prompt." - ) - - async def test_should_answer_with_high_score_provided_context(self): - qna = QnAMaker(QnaApplicationTest.tests_endpoint) - question: str = "where can I buy?" - context = QnARequestContext( - previous_qna_id=5, prvious_user_query="how do I clean the stove?" - ) - options = QnAMakerOptions(top=2, qna_id=55, context=context) - turn_context = QnaApplicationTest._get_context(question, TestAdapter()) - response_json = QnaApplicationTest._get_json_for_file( - "AnswerWithHighScoreProvidedContext.json" - ) - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers(turn_context, options) - self.assertEqual(1, len(results), "Should have received 1 answers.") - self.assertEqual(1, results[0].score, "Score should be high.") - - async def test_should_answer_with_high_score_provided_qna_id(self): - qna = QnAMaker(QnaApplicationTest.tests_endpoint) - question: str = "where can I buy?" - - options = QnAMakerOptions(top=2, qna_id=55) - turn_context = QnaApplicationTest._get_context(question, TestAdapter()) - response_json = QnaApplicationTest._get_json_for_file( - "AnswerWithHighScoreProvidedContext.json" - ) - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers(turn_context, options) - self.assertEqual(1, len(results), "Should have received 1 answers.") - self.assertEqual(1, results[0].score, "Score should be high.") - - async def test_should_answer_with_low_score_without_provided_context(self): - qna = QnAMaker(QnaApplicationTest.tests_endpoint) - question: str = "where can I buy?" - options = QnAMakerOptions(top=2, context=None) - - turn_context = QnaApplicationTest._get_context(question, TestAdapter()) - response_json = QnaApplicationTest._get_json_for_file( - "AnswerWithLowScoreProvidedWithoutContext.json" - ) - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - results = await qna.get_answers(turn_context, options) - self.assertEqual( - 2, len(results), "Should have received more than one answers." - ) - self.assertEqual(True, results[0].score < 1, "Score should be low.") - - @classmethod - async def _get_service_result( - cls, - utterance: str, - response_file: str, - bot_adapter: BotAdapter = TestAdapter(), - options: QnAMakerOptions = None, - ) -> [dict]: - response_json = QnaApplicationTest._get_json_for_file(response_file) - - qna = QnAMaker(QnaApplicationTest.tests_endpoint) - context = QnaApplicationTest._get_context(utterance, bot_adapter) - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - result = await qna.get_answers(context, options) - - return result - - @classmethod - async def _get_service_result_raw( - cls, - utterance: str, - response_file: str, - bot_adapter: BotAdapter = TestAdapter(), - options: QnAMakerOptions = None, - ) -> [dict]: - response_json = QnaApplicationTest._get_json_for_file(response_file) - - qna = QnAMaker(QnaApplicationTest.tests_endpoint) - context = QnaApplicationTest._get_context(utterance, bot_adapter) - - with patch( - "aiohttp.ClientSession.post", - return_value=aiounittest.futurized(response_json), - ): - result = await qna.get_answers_raw(context, options) - - return result - - @classmethod - def _get_json_for_file(cls, response_file: str) -> object: - curr_dir = path.dirname(path.abspath(__file__)) - response_path = path.join(curr_dir, "test_data", response_file) - - with open(response_path, "r", encoding="utf-8-sig") as file: - response_str = file.read() - response_json = json.loads(response_str) - - return response_json - - @staticmethod - def _get_context(question: str, bot_adapter: BotAdapter) -> TurnContext: - test_adapter = bot_adapter or TestAdapter() - activity = Activity( - type=ActivityTypes.message, - text=question, - conversation=ConversationAccount(), - recipient=ChannelAccount(), - from_property=ChannelAccount(), - ) - - return TurnContext(test_adapter, activity) - - class OverrideTelemetry(QnAMaker): - def __init__( # pylint: disable=useless-super-delegation - self, - endpoint: QnAMakerEndpoint, - options: QnAMakerOptions, - http_client: ClientSession, - telemetry_client: BotTelemetryClient, - log_personal_information: bool, - ): - super().__init__( - endpoint, - options, - http_client, - telemetry_client, - log_personal_information, - ) - - async def on_qna_result( # pylint: disable=unused-argument - self, - query_results: [QueryResult], - turn_context: TurnContext, - telemetry_properties: Dict[str, str] = None, - telemetry_metrics: Dict[str, float] = None, - ): - properties = telemetry_properties or {} - - # get_answers overrides derived class - properties["my_important_property"] = "my_important_value" - - # Log event - self.telemetry_client.track_event( - QnATelemetryConstants.qna_message_event, properties - ) - - # Create 2nd event. - second_event_properties = {"my_important_property2": "my_important_value2"} - self.telemetry_client.track_event( - "my_second_event", second_event_properties - ) - - class OverrideFillTelemetry(QnAMaker): - def __init__( # pylint: disable=useless-super-delegation - self, - endpoint: QnAMakerEndpoint, - options: QnAMakerOptions, - http_client: ClientSession, - telemetry_client: BotTelemetryClient, - log_personal_information: bool, - ): - super().__init__( - endpoint, - options, - http_client, - telemetry_client, - log_personal_information, - ) - - async def on_qna_result( - self, - query_results: [QueryResult], - turn_context: TurnContext, - telemetry_properties: Dict[str, str] = None, - telemetry_metrics: Dict[str, float] = None, - ): - event_data = await self.fill_qna_event( - query_results, turn_context, telemetry_properties, telemetry_metrics - ) - - # Add my property. - event_data.properties.update( - {"my_important_property": "my_important_value"} - ) - - # Log QnaMessage event. - self.telemetry_client.track_event( - QnATelemetryConstants.qna_message_event, - event_data.properties, - event_data.metrics, - ) - - # Create second event. - second_event_properties: Dict[str, str] = { - "my_important_property2": "my_important_value2" - } - - self.telemetry_client.track_event("MySecondEvent", second_event_properties) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +# pylint: disable=protected-access + +import json +from os import path +from typing import List, Dict +import unittest +from unittest.mock import patch +from aiohttp import ClientSession + +import aiounittest +from botbuilder.ai.qna import QnAMakerEndpoint, QnAMaker, QnAMakerOptions +from botbuilder.ai.qna.models import ( + FeedbackRecord, + Metadata, + QueryResult, + QnARequestContext, +) +from botbuilder.ai.qna.utils import QnATelemetryConstants +from botbuilder.core import BotAdapter, BotTelemetryClient, TurnContext +from botbuilder.core.adapters import TestAdapter +from botbuilder.schema import ( + Activity, + ActivityTypes, + ChannelAccount, + ConversationAccount, +) + + +class TestContext(TurnContext): + __test__ = False + + def __init__(self, request): + super().__init__(TestAdapter(), request) + self.sent: List[Activity] = list() + + self.on_send_activities(self.capture_sent_activities) + + async def capture_sent_activities( + self, context: TurnContext, activities, next + ): # pylint: disable=unused-argument + self.sent += activities + context.responded = True + + +class QnaApplicationTest(aiounittest.AsyncTestCase): + # Note this is NOT a real QnA Maker application ID nor a real QnA Maker subscription-key + # theses are GUIDs edited to look right to the parsing and validation code. + + _knowledge_base_id: str = "f028d9k3-7g9z-11d3-d300-2b8x98227q8w" + _endpoint_key: str = "1k997n7w-207z-36p3-j2u1-09tas20ci6011" + _host: str = "https://dummyqnahost.azurewebsites.net/qnamaker" + + tests_endpoint = QnAMakerEndpoint(_knowledge_base_id, _endpoint_key, _host) + + def test_qnamaker_construction(self): + # Arrange + endpoint = self.tests_endpoint + + # Act + qna = QnAMaker(endpoint) + endpoint = qna._endpoint + + # Assert + self.assertEqual( + "f028d9k3-7g9z-11d3-d300-2b8x98227q8w", endpoint.knowledge_base_id + ) + self.assertEqual("1k997n7w-207z-36p3-j2u1-09tas20ci6011", endpoint.endpoint_key) + self.assertEqual( + "https://dummyqnahost.azurewebsites.net/qnamaker", endpoint.host + ) + + def test_endpoint_with_empty_kbid(self): + empty_kbid = "" + + with self.assertRaises(TypeError): + QnAMakerEndpoint(empty_kbid, self._endpoint_key, self._host) + + def test_endpoint_with_empty_endpoint_key(self): + empty_endpoint_key = "" + + with self.assertRaises(TypeError): + QnAMakerEndpoint(self._knowledge_base_id, empty_endpoint_key, self._host) + + def test_endpoint_with_emptyhost(self): + with self.assertRaises(TypeError): + QnAMakerEndpoint(self._knowledge_base_id, self._endpoint_key, "") + + def test_qnamaker_with_none_endpoint(self): + with self.assertRaises(TypeError): + QnAMaker(None) + + def test_set_default_options_with_no_options_arg(self): + qna_without_options = QnAMaker(self.tests_endpoint) + options = qna_without_options._generate_answer_helper.options + + default_threshold = 0.3 + default_top = 1 + default_strict_filters = [] + + self.assertEqual(default_threshold, options.score_threshold) + self.assertEqual(default_top, options.top) + self.assertEqual(default_strict_filters, options.strict_filters) + + def test_options_passed_to_ctor(self): + options = QnAMakerOptions( + score_threshold=0.8, + timeout=9000, + top=5, + strict_filters=[Metadata("movie", "disney")], + ) + + qna_with_options = QnAMaker(self.tests_endpoint, options) + actual_options = qna_with_options._generate_answer_helper.options + + expected_threshold = 0.8 + expected_timeout = 9000 + expected_top = 5 + expected_strict_filters = [Metadata("movie", "disney")] + + self.assertEqual(expected_threshold, actual_options.score_threshold) + self.assertEqual(expected_timeout, actual_options.timeout) + self.assertEqual(expected_top, actual_options.top) + self.assertEqual( + expected_strict_filters[0].name, actual_options.strict_filters[0].name + ) + self.assertEqual( + expected_strict_filters[0].value, actual_options.strict_filters[0].value + ) + + async def test_returns_answer(self): + # Arrange + question: str = "how do I clean the stove?" + response_path: str = "ReturnsAnswer.json" + + # Act + result = await QnaApplicationTest._get_service_result(question, response_path) + + first_answer = result[0] + + # Assert + self.assertIsNotNone(result) + self.assertEqual(1, len(result)) + self.assertEqual( + "BaseCamp: You can use a damp rag to clean around the Power Pack", + first_answer.answer, + ) + + async def test_active_learning_enabled_status(self): + # Arrange + question: str = "how do I clean the stove?" + response_path: str = "ReturnsAnswer.json" + + # Act + result = await QnaApplicationTest._get_service_result_raw( + question, response_path + ) + + # Assert + self.assertIsNotNone(result) + self.assertEqual(1, len(result.answers)) + self.assertFalse(result.active_learning_enabled) + + async def test_returns_answer_using_options(self): + # Arrange + question: str = "up" + response_path: str = "AnswerWithOptions.json" + options = QnAMakerOptions( + score_threshold=0.8, top=5, strict_filters=[Metadata("movie", "disney")] + ) + + # Act + result = await QnaApplicationTest._get_service_result( + question, response_path, options=options + ) + + first_answer = result[0] + has_at_least_1_ans = True + first_metadata = first_answer.metadata[0] + + # Assert + self.assertIsNotNone(result) + self.assertEqual(has_at_least_1_ans, len(result) >= 1) + self.assertTrue(first_answer.answer[0]) + self.assertEqual("is a movie", first_answer.answer) + self.assertTrue(first_answer.score >= options.score_threshold) + self.assertEqual("movie", first_metadata.name) + self.assertEqual("disney", first_metadata.value) + + async def test_trace_test(self): + activity = Activity( + type=ActivityTypes.message, + text="how do I clean the stove?", + conversation=ConversationAccount(), + recipient=ChannelAccount(), + from_property=ChannelAccount(), + ) + + response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") + qna = QnAMaker(QnaApplicationTest.tests_endpoint) + + context = TestContext(activity) + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + result = await qna.get_answers(context) + + qna_trace_activities = list( + filter( + lambda act: act.type == "trace" and act.name == "QnAMaker", + context.sent, + ) + ) + trace_activity = qna_trace_activities[0] + + self.assertEqual("trace", trace_activity.type) + self.assertEqual("QnAMaker", trace_activity.name) + self.assertEqual("QnAMaker Trace", trace_activity.label) + self.assertEqual( + "https://www.qnamaker.ai/schemas/trace", trace_activity.value_type + ) + self.assertEqual(True, hasattr(trace_activity, "value")) + self.assertEqual(True, hasattr(trace_activity.value, "message")) + self.assertEqual(True, hasattr(trace_activity.value, "query_results")) + self.assertEqual(True, hasattr(trace_activity.value, "score_threshold")) + self.assertEqual(True, hasattr(trace_activity.value, "top")) + self.assertEqual(True, hasattr(trace_activity.value, "strict_filters")) + self.assertEqual( + self._knowledge_base_id, trace_activity.value.knowledge_base_id + ) + + return result + + async def test_returns_answer_with_timeout(self): + question: str = "how do I clean the stove?" + options = QnAMakerOptions(timeout=999999) + qna = QnAMaker(QnaApplicationTest.tests_endpoint, options) + context = QnaApplicationTest._get_context(question, TestAdapter()) + response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + result = await qna.get_answers(context, options) + + self.assertIsNotNone(result) + self.assertEqual( + options.timeout, qna._generate_answer_helper.options.timeout + ) + + async def test_telemetry_returns_answer(self): + # Arrange + question: str = "how do I clean the stove?" + response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = True + context = QnaApplicationTest._get_context(question, TestAdapter()) + qna = QnAMaker( + QnaApplicationTest.tests_endpoint, + telemetry_client=telemetry_client, + log_personal_information=log_personal_information, + ) + + # Act + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(context) + + telemetry_args = telemetry_client.track_event.call_args_list[0][1] + telemetry_properties = telemetry_args["properties"] + telemetry_metrics = telemetry_args["measurements"] + number_of_args = len(telemetry_args) + first_answer = telemetry_args["properties"][ + QnATelemetryConstants.answer_property + ] + expected_answer = ( + "BaseCamp: You can use a damp rag to clean around the Power Pack" + ) + + # Assert - Check Telemetry logged. + self.assertEqual(1, telemetry_client.track_event.call_count) + self.assertEqual(3, number_of_args) + self.assertEqual("QnaMessage", telemetry_args["name"]) + self.assertTrue("answer" in telemetry_properties) + self.assertTrue("knowledgeBaseId" in telemetry_properties) + self.assertTrue("matchedQuestion" in telemetry_properties) + self.assertTrue("question" in telemetry_properties) + self.assertTrue("questionId" in telemetry_properties) + self.assertTrue("articleFound" in telemetry_properties) + self.assertEqual(expected_answer, first_answer) + self.assertTrue("score" in telemetry_metrics) + self.assertEqual(1, telemetry_metrics["score"]) + + # Assert - Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer) + self.assertEqual("Editorial", results[0].source) + + async def test_telemetry_returns_answer_when_no_answer_found_in_kb(self): + # Arrange + question: str = "gibberish question" + response_json = QnaApplicationTest._get_json_for_file("NoAnswerFoundInKb.json") + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + qna = QnAMaker( + QnaApplicationTest.tests_endpoint, + telemetry_client=telemetry_client, + log_personal_information=True, + ) + context = QnaApplicationTest._get_context(question, TestAdapter()) + + # Act + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(context) + + telemetry_args = telemetry_client.track_event.call_args_list[0][1] + telemetry_properties = telemetry_args["properties"] + number_of_args = len(telemetry_args) + first_answer = telemetry_args["properties"][ + QnATelemetryConstants.answer_property + ] + expected_answer = "No Qna Answer matched" + expected_matched_question = "No Qna Question matched" + + # Assert - Check Telemetry logged. + self.assertEqual(1, telemetry_client.track_event.call_count) + self.assertEqual(3, number_of_args) + self.assertEqual("QnaMessage", telemetry_args["name"]) + self.assertTrue("answer" in telemetry_properties) + self.assertTrue("knowledgeBaseId" in telemetry_properties) + self.assertTrue("matchedQuestion" in telemetry_properties) + self.assertEqual( + expected_matched_question, + telemetry_properties[QnATelemetryConstants.matched_question_property], + ) + self.assertTrue("question" in telemetry_properties) + self.assertTrue("questionId" in telemetry_properties) + self.assertTrue("articleFound" in telemetry_properties) + self.assertEqual(expected_answer, first_answer) + + # Assert - Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(0, len(results)) + + async def test_telemetry_pii(self): + # Arrange + question: str = "how do I clean the stove?" + response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = False + context = QnaApplicationTest._get_context(question, TestAdapter()) + qna = QnAMaker( + QnaApplicationTest.tests_endpoint, + telemetry_client=telemetry_client, + log_personal_information=log_personal_information, + ) + + # Act + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(context) + + telemetry_args = telemetry_client.track_event.call_args_list[0][1] + telemetry_properties = telemetry_args["properties"] + telemetry_metrics = telemetry_args["measurements"] + number_of_args = len(telemetry_args) + first_answer = telemetry_args["properties"][ + QnATelemetryConstants.answer_property + ] + expected_answer = ( + "BaseCamp: You can use a damp rag to clean around the Power Pack" + ) + + # Assert - Validate PII properties not logged. + self.assertEqual(1, telemetry_client.track_event.call_count) + self.assertEqual(3, number_of_args) + self.assertEqual("QnaMessage", telemetry_args["name"]) + self.assertTrue("answer" in telemetry_properties) + self.assertTrue("knowledgeBaseId" in telemetry_properties) + self.assertTrue("matchedQuestion" in telemetry_properties) + self.assertTrue("question" not in telemetry_properties) + self.assertTrue("questionId" in telemetry_properties) + self.assertTrue("articleFound" in telemetry_properties) + self.assertEqual(expected_answer, first_answer) + self.assertTrue("score" in telemetry_metrics) + self.assertEqual(1, telemetry_metrics["score"]) + + # Assert - Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer) + self.assertEqual("Editorial", results[0].source) + + async def test_telemetry_override(self): + # Arrange + question: str = "how do I clean the stove?" + response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") + context = QnaApplicationTest._get_context(question, TestAdapter()) + options = QnAMakerOptions(top=1) + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = False + + # Act - Override the QnAMaker object to log custom stuff and honor params passed in. + telemetry_properties: Dict[str, str] = {"id": "MyId"} + qna = QnaApplicationTest.OverrideTelemetry( + QnaApplicationTest.tests_endpoint, + options, + None, + telemetry_client, + log_personal_information, + ) + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(context, options, telemetry_properties) + + telemetry_args = telemetry_client.track_event.call_args_list + first_call_args = telemetry_args[0][0] + first_call_properties = first_call_args[1] + second_call_args = telemetry_args[1][0] + second_call_properties = second_call_args[1] + expected_answer = ( + "BaseCamp: You can use a damp rag to clean around the Power Pack" + ) + + # Assert + self.assertEqual(2, telemetry_client.track_event.call_count) + self.assertEqual(2, len(first_call_args)) + self.assertEqual("QnaMessage", first_call_args[0]) + self.assertEqual(2, len(first_call_properties)) + self.assertTrue("my_important_property" in first_call_properties) + self.assertEqual( + "my_important_value", first_call_properties["my_important_property"] + ) + self.assertTrue("id" in first_call_properties) + self.assertEqual("MyId", first_call_properties["id"]) + + self.assertEqual("my_second_event", second_call_args[0]) + self.assertTrue("my_important_property2" in second_call_properties) + self.assertEqual( + "my_important_value2", second_call_properties["my_important_property2"] + ) + + # Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer) + self.assertEqual("Editorial", results[0].source) + + async def test_telemetry_additional_props_metrics(self): + # Arrange + question: str = "how do I clean the stove?" + response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") + context = QnaApplicationTest._get_context(question, TestAdapter()) + options = QnAMakerOptions(top=1) + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = False + + # Act + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + qna = QnAMaker( + QnaApplicationTest.tests_endpoint, + options, + None, + telemetry_client, + log_personal_information, + ) + telemetry_properties: Dict[str, str] = { + "my_important_property": "my_important_value" + } + telemetry_metrics: Dict[str, float] = {"my_important_metric": 3.14159} + + results = await qna.get_answers( + context, None, telemetry_properties, telemetry_metrics + ) + + # Assert - Added properties were added. + telemetry_args = telemetry_client.track_event.call_args_list[0][1] + telemetry_properties = telemetry_args["properties"] + expected_answer = ( + "BaseCamp: You can use a damp rag to clean around the Power Pack" + ) + + self.assertEqual(1, telemetry_client.track_event.call_count) + self.assertEqual(3, len(telemetry_args)) + self.assertEqual("QnaMessage", telemetry_args["name"]) + self.assertTrue("knowledgeBaseId" in telemetry_properties) + self.assertTrue("question" not in telemetry_properties) + self.assertTrue("matchedQuestion" in telemetry_properties) + self.assertTrue("questionId" in telemetry_properties) + self.assertTrue("answer" in telemetry_properties) + self.assertTrue(expected_answer, telemetry_properties["answer"]) + self.assertTrue("my_important_property" in telemetry_properties) + self.assertEqual( + "my_important_value", telemetry_properties["my_important_property"] + ) + + tracked_metrics = telemetry_args["measurements"] + + self.assertEqual(2, len(tracked_metrics)) + self.assertTrue("score" in tracked_metrics) + self.assertTrue("my_important_metric" in tracked_metrics) + self.assertEqual(3.14159, tracked_metrics["my_important_metric"]) + + # Assert - Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer) + self.assertEqual("Editorial", results[0].source) + + async def test_telemetry_additional_props_override(self): + question: str = "how do I clean the stove?" + response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") + context = QnaApplicationTest._get_context(question, TestAdapter()) + options = QnAMakerOptions(top=1) + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = False + + # Act - Pass in properties during QnA invocation that override default properties + # NOTE: We are invoking this with PII turned OFF, and passing a PII property (originalQuestion). + qna = QnAMaker( + QnaApplicationTest.tests_endpoint, + options, + None, + telemetry_client, + log_personal_information, + ) + telemetry_properties = { + "knowledge_base_id": "my_important_value", + "original_question": "my_important_value2", + } + telemetry_metrics = {"score": 3.14159} + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers( + context, None, telemetry_properties, telemetry_metrics + ) + + # Assert - Added properties were added. + tracked_args = telemetry_client.track_event.call_args_list[0][1] + tracked_properties = tracked_args["properties"] + expected_answer = ( + "BaseCamp: You can use a damp rag to clean around the Power Pack" + ) + tracked_metrics = tracked_args["measurements"] + + self.assertEqual(1, telemetry_client.track_event.call_count) + self.assertEqual(3, len(tracked_args)) + self.assertEqual("QnaMessage", tracked_args["name"]) + self.assertTrue("knowledge_base_id" in tracked_properties) + self.assertEqual( + "my_important_value", tracked_properties["knowledge_base_id"] + ) + self.assertTrue("original_question" in tracked_properties) + self.assertTrue("matchedQuestion" in tracked_properties) + self.assertEqual( + "my_important_value2", tracked_properties["original_question"] + ) + self.assertTrue("question" not in tracked_properties) + self.assertTrue("questionId" in tracked_properties) + self.assertTrue("answer" in tracked_properties) + self.assertEqual(expected_answer, tracked_properties["answer"]) + self.assertTrue("my_important_property" not in tracked_properties) + self.assertEqual(1, len(tracked_metrics)) + self.assertTrue("score" in tracked_metrics) + self.assertEqual(3.14159, tracked_metrics["score"]) + + # Assert - Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer) + self.assertEqual("Editorial", results[0].source) + + async def test_telemetry_fill_props_override(self): + # Arrange + question: str = "how do I clean the stove?" + response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json") + context: TurnContext = QnaApplicationTest._get_context(question, TestAdapter()) + options = QnAMakerOptions(top=1) + telemetry_client = unittest.mock.create_autospec(BotTelemetryClient) + log_personal_information = False + + # Act - Pass in properties during QnA invocation that override default properties + # In addition Override with derivation. This presents an interesting question of order of setting + # properties. + # If I want to override "originalQuestion" property: + # - Set in "Stock" schema + # - Set in derived QnAMaker class + # - Set in GetAnswersAsync + # Logically, the GetAnswersAync should win. But ultimately OnQnaResultsAsync decides since it is the last + # code to touch the properties before logging (since it actually logs the event). + qna = QnaApplicationTest.OverrideFillTelemetry( + QnaApplicationTest.tests_endpoint, + options, + None, + telemetry_client, + log_personal_information, + ) + telemetry_properties: Dict[str, str] = { + "knowledgeBaseId": "my_important_value", + "matchedQuestion": "my_important_value2", + } + telemetry_metrics: Dict[str, float] = {"score": 3.14159} + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers( + context, None, telemetry_properties, telemetry_metrics + ) + + # Assert - Added properties were added. + first_call_args = telemetry_client.track_event.call_args_list[0][0] + first_properties = first_call_args[1] + expected_answer = ( + "BaseCamp: You can use a damp rag to clean around the Power Pack" + ) + first_metrics = first_call_args[2] + + self.assertEqual(2, telemetry_client.track_event.call_count) + self.assertEqual(3, len(first_call_args)) + self.assertEqual("QnaMessage", first_call_args[0]) + self.assertEqual(6, len(first_properties)) + self.assertTrue("knowledgeBaseId" in first_properties) + self.assertEqual("my_important_value", first_properties["knowledgeBaseId"]) + self.assertTrue("matchedQuestion" in first_properties) + self.assertEqual("my_important_value2", first_properties["matchedQuestion"]) + self.assertTrue("questionId" in first_properties) + self.assertTrue("answer" in first_properties) + self.assertEqual(expected_answer, first_properties["answer"]) + self.assertTrue("articleFound" in first_properties) + self.assertTrue("my_important_property" in first_properties) + self.assertEqual( + "my_important_value", first_properties["my_important_property"] + ) + + self.assertEqual(1, len(first_metrics)) + self.assertTrue("score" in first_metrics) + self.assertEqual(3.14159, first_metrics["score"]) + + # Assert - Validate we didn't break QnA functionality. + self.assertIsNotNone(results) + self.assertEqual(1, len(results)) + self.assertEqual(expected_answer, results[0].answer) + self.assertEqual("Editorial", results[0].source) + + async def test_call_train(self): + feedback_records = [] + + feedback1 = FeedbackRecord( + qna_id=1, user_id="test", user_question="How are you?" + ) + + feedback2 = FeedbackRecord(qna_id=2, user_id="test", user_question="What up??") + + feedback_records.extend([feedback1, feedback2]) + + with patch.object( + QnAMaker, "call_train", return_value=None + ) as mocked_call_train: + qna = QnAMaker(QnaApplicationTest.tests_endpoint) + qna.call_train(feedback_records) + + mocked_call_train.assert_called_once_with(feedback_records) + + async def test_should_filter_low_score_variation(self): + options = QnAMakerOptions(top=5) + qna = QnAMaker(QnaApplicationTest.tests_endpoint, options) + question: str = "Q11" + context = QnaApplicationTest._get_context(question, TestAdapter()) + response_json = QnaApplicationTest._get_json_for_file("TopNAnswer.json") + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(context) + self.assertEqual(4, len(results), "Should have received 4 answers.") + + filtered_results = qna.get_low_score_variation(results) + self.assertEqual( + 3, + len(filtered_results), + "Should have 3 filtered answers after low score variation.", + ) + + async def test_should_answer_with_is_test_true(self): + options = QnAMakerOptions(top=1, is_test=True) + qna = QnAMaker(QnaApplicationTest.tests_endpoint) + question: str = "Q11" + context = QnaApplicationTest._get_context(question, TestAdapter()) + response_json = QnaApplicationTest._get_json_for_file( + "QnaMaker_IsTest_true.json" + ) + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(context, options=options) + self.assertEqual(0, len(results), "Should have received zero answer.") + + async def test_should_answer_with_ranker_type_question_only(self): + options = QnAMakerOptions(top=1, ranker_type="QuestionOnly") + qna = QnAMaker(QnaApplicationTest.tests_endpoint) + question: str = "Q11" + context = QnaApplicationTest._get_context(question, TestAdapter()) + response_json = QnaApplicationTest._get_json_for_file( + "QnaMaker_RankerType_QuestionOnly.json" + ) + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(context, options=options) + self.assertEqual(2, len(results), "Should have received two answers.") + + async def test_should_answer_with_prompts(self): + options = QnAMakerOptions(top=2) + qna = QnAMaker(QnaApplicationTest.tests_endpoint, options) + question: str = "how do I clean the stove?" + turn_context = QnaApplicationTest._get_context(question, TestAdapter()) + response_json = QnaApplicationTest._get_json_for_file("AnswerWithPrompts.json") + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(turn_context, options) + self.assertEqual(1, len(results), "Should have received 1 answers.") + self.assertEqual( + 1, len(results[0].context.prompts), "Should have received 1 prompt." + ) + + async def test_should_answer_with_high_score_provided_context(self): + qna = QnAMaker(QnaApplicationTest.tests_endpoint) + question: str = "where can I buy?" + context = QnARequestContext( + previous_qna_id=5, prvious_user_query="how do I clean the stove?" + ) + options = QnAMakerOptions(top=2, qna_id=55, context=context) + turn_context = QnaApplicationTest._get_context(question, TestAdapter()) + response_json = QnaApplicationTest._get_json_for_file( + "AnswerWithHighScoreProvidedContext.json" + ) + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(turn_context, options) + self.assertEqual(1, len(results), "Should have received 1 answers.") + self.assertEqual(1, results[0].score, "Score should be high.") + + async def test_should_answer_with_high_score_provided_qna_id(self): + qna = QnAMaker(QnaApplicationTest.tests_endpoint) + question: str = "where can I buy?" + + options = QnAMakerOptions(top=2, qna_id=55) + turn_context = QnaApplicationTest._get_context(question, TestAdapter()) + response_json = QnaApplicationTest._get_json_for_file( + "AnswerWithHighScoreProvidedContext.json" + ) + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(turn_context, options) + self.assertEqual(1, len(results), "Should have received 1 answers.") + self.assertEqual(1, results[0].score, "Score should be high.") + + async def test_should_answer_with_low_score_without_provided_context(self): + qna = QnAMaker(QnaApplicationTest.tests_endpoint) + question: str = "where can I buy?" + options = QnAMakerOptions(top=2, context=None) + + turn_context = QnaApplicationTest._get_context(question, TestAdapter()) + response_json = QnaApplicationTest._get_json_for_file( + "AnswerWithLowScoreProvidedWithoutContext.json" + ) + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(turn_context, options) + self.assertEqual( + 2, len(results), "Should have received more than one answers." + ) + self.assertEqual(True, results[0].score < 1, "Score should be low.") + + @classmethod + async def _get_service_result( + cls, + utterance: str, + response_file: str, + bot_adapter: BotAdapter = TestAdapter(), + options: QnAMakerOptions = None, + ) -> [dict]: + response_json = QnaApplicationTest._get_json_for_file(response_file) + + qna = QnAMaker(QnaApplicationTest.tests_endpoint) + context = QnaApplicationTest._get_context(utterance, bot_adapter) + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + result = await qna.get_answers(context, options) + + return result + + @classmethod + async def _get_service_result_raw( + cls, + utterance: str, + response_file: str, + bot_adapter: BotAdapter = TestAdapter(), + options: QnAMakerOptions = None, + ) -> [dict]: + response_json = QnaApplicationTest._get_json_for_file(response_file) + + qna = QnAMaker(QnaApplicationTest.tests_endpoint) + context = QnaApplicationTest._get_context(utterance, bot_adapter) + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + result = await qna.get_answers_raw(context, options) + + return result + + @classmethod + def _get_json_for_file(cls, response_file: str) -> object: + curr_dir = path.dirname(path.abspath(__file__)) + response_path = path.join(curr_dir, "test_data", response_file) + + with open(response_path, "r", encoding="utf-8-sig") as file: + response_str = file.read() + response_json = json.loads(response_str) + + return response_json + + @staticmethod + def _get_context(question: str, bot_adapter: BotAdapter) -> TurnContext: + test_adapter = bot_adapter or TestAdapter() + activity = Activity( + type=ActivityTypes.message, + text=question, + conversation=ConversationAccount(), + recipient=ChannelAccount(), + from_property=ChannelAccount(), + ) + + return TurnContext(test_adapter, activity) + + class OverrideTelemetry(QnAMaker): + def __init__( # pylint: disable=useless-super-delegation + self, + endpoint: QnAMakerEndpoint, + options: QnAMakerOptions, + http_client: ClientSession, + telemetry_client: BotTelemetryClient, + log_personal_information: bool, + ): + super().__init__( + endpoint, + options, + http_client, + telemetry_client, + log_personal_information, + ) + + async def on_qna_result( # pylint: disable=unused-argument + self, + query_results: [QueryResult], + turn_context: TurnContext, + telemetry_properties: Dict[str, str] = None, + telemetry_metrics: Dict[str, float] = None, + ): + properties = telemetry_properties or {} + + # get_answers overrides derived class + properties["my_important_property"] = "my_important_value" + + # Log event + self.telemetry_client.track_event( + QnATelemetryConstants.qna_message_event, properties + ) + + # Create 2nd event. + second_event_properties = {"my_important_property2": "my_important_value2"} + self.telemetry_client.track_event( + "my_second_event", second_event_properties + ) + + class OverrideFillTelemetry(QnAMaker): + def __init__( # pylint: disable=useless-super-delegation + self, + endpoint: QnAMakerEndpoint, + options: QnAMakerOptions, + http_client: ClientSession, + telemetry_client: BotTelemetryClient, + log_personal_information: bool, + ): + super().__init__( + endpoint, + options, + http_client, + telemetry_client, + log_personal_information, + ) + + async def on_qna_result( + self, + query_results: [QueryResult], + turn_context: TurnContext, + telemetry_properties: Dict[str, str] = None, + telemetry_metrics: Dict[str, float] = None, + ): + event_data = await self.fill_qna_event( + query_results, turn_context, telemetry_properties, telemetry_metrics + ) + + # Add my property. + event_data.properties.update( + {"my_important_property": "my_important_value"} + ) + + # Log QnaMessage event. + self.telemetry_client.track_event( + QnATelemetryConstants.qna_message_event, + event_data.properties, + event_data.metrics, + ) + + # Create second event. + second_event_properties: Dict[str, str] = { + "my_important_property2": "my_important_value2" + } + + self.telemetry_client.track_event("MySecondEvent", second_event_properties) diff --git a/libraries/botbuilder-applicationinsights/tests/test_telemetry_waterfall.py b/libraries/botbuilder-applicationinsights/tests/test_telemetry_waterfall.py --- a/libraries/botbuilder-applicationinsights/tests/test_telemetry_waterfall.py +++ b/libraries/botbuilder-applicationinsights/tests/test_telemetry_waterfall.py @@ -1,178 +1,174 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -from unittest.mock import patch -from typing import Dict -import aiounittest -from botbuilder.core.adapters import TestAdapter, TestFlow -from botbuilder.schema import Activity -from botbuilder.core import ( - ConversationState, - MemoryStorage, - TurnContext, - NullTelemetryClient, -) -from botbuilder.dialogs import ( - Dialog, - DialogSet, - WaterfallDialog, - DialogTurnResult, - DialogTurnStatus, -) - -BEGIN_MESSAGE = Activity() -BEGIN_MESSAGE.text = "begin" -BEGIN_MESSAGE.type = "message" - - -class TelemetryWaterfallTests(aiounittest.AsyncTestCase): - def test_none_telemetry_client(self): - # arrange - dialog = WaterfallDialog("myId") - # act - dialog.telemetry_client = None - # assert - self.assertEqual(type(dialog.telemetry_client), NullTelemetryClient) - - @patch("botbuilder.applicationinsights.ApplicationInsightsTelemetryClient") - async def test_execute_sequence_waterfall_steps( # pylint: disable=invalid-name - self, MockTelemetry - ): - # arrange - - # Create new ConversationState with MemoryStorage and register the state as middleware. - convo_state = ConversationState(MemoryStorage()) - telemetry = MockTelemetry() - - # Create a DialogState property, DialogSet and register the WaterfallDialog. - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - async def step1(step) -> DialogTurnResult: - await step.context.send_activity("bot responding.") - return Dialog.end_of_turn - - async def step2(step) -> DialogTurnResult: - await step.context.send_activity("ending WaterfallDialog.") - return Dialog.end_of_turn - - # act - - my_dialog = WaterfallDialog("test", [step1, step2]) - my_dialog.telemetry_client = telemetry - dialogs.add(my_dialog) - - # Initialize TestAdapter - async def exec_test(turn_context: TurnContext) -> None: - - dialog_context = await dialogs.create_context(turn_context) - results = await dialog_context.continue_dialog() - if results.status == DialogTurnStatus.Empty: - await dialog_context.begin_dialog("test") - else: - if results.status == DialogTurnStatus.Complete: - await turn_context.send_activity(results.result) - - await convo_state.save_changes(turn_context) - - adapt = TestAdapter(exec_test) - - test_flow = TestFlow(None, adapt) - tf2 = await test_flow.send(BEGIN_MESSAGE) - tf3 = await tf2.assert_reply("bot responding.") - tf4 = await tf3.send("continue") - await tf4.assert_reply("ending WaterfallDialog.") - - # assert - - telemetry_calls = [ - ("WaterfallStart", {"DialogId": "test"}), - ("WaterfallStep", {"DialogId": "test", "StepName": "Step1of2"}), - ("WaterfallStep", {"DialogId": "test", "StepName": "Step2of2"}), - ] - self.assert_telemetry_calls(telemetry, telemetry_calls) - - @patch("botbuilder.applicationinsights.ApplicationInsightsTelemetryClient") - async def test_ensure_end_dialog_called( - self, MockTelemetry - ): # pylint: disable=invalid-name - # arrange - - # Create new ConversationState with MemoryStorage and register the state as middleware. - convo_state = ConversationState(MemoryStorage()) - telemetry = MockTelemetry() - - # Create a DialogState property, DialogSet and register the WaterfallDialog. - dialog_state = convo_state.create_property("dialogState") - dialogs = DialogSet(dialog_state) - - async def step1(step) -> DialogTurnResult: - await step.context.send_activity("step1 response") - return Dialog.end_of_turn - - async def step2(step) -> DialogTurnResult: - await step.context.send_activity("step2 response") - return Dialog.end_of_turn - - # act - - my_dialog = WaterfallDialog("test", [step1, step2]) - my_dialog.telemetry_client = telemetry - dialogs.add(my_dialog) - - # Initialize TestAdapter - async def exec_test(turn_context: TurnContext) -> None: - - dialog_context = await dialogs.create_context(turn_context) - await dialog_context.continue_dialog() - if not turn_context.responded: - await dialog_context.begin_dialog("test", None) - await convo_state.save_changes(turn_context) - - adapt = TestAdapter(exec_test) - - test_flow = TestFlow(None, adapt) - tf2 = await test_flow.send(BEGIN_MESSAGE) - tf3 = await tf2.assert_reply("step1 response") - tf4 = await tf3.send("continue") - tf5 = await tf4.assert_reply("step2 response") - await tf5.send( - "Should hit end of steps - this will restart the dialog and trigger COMPLETE event" - ) - # assert - telemetry_calls = [ - ("WaterfallStart", {"DialogId": "test"}), - ("WaterfallStep", {"DialogId": "test", "StepName": "Step1of2"}), - ("WaterfallStep", {"DialogId": "test", "StepName": "Step2of2"}), - ("WaterfallComplete", {"DialogId": "test"}), - ("WaterfallStart", {"DialogId": "test"}), - ("WaterfallStep", {"DialogId": "test", "StepName": "Step1of2"}), - ] - print(str(telemetry.track_event.call_args_list)) - self.assert_telemetry_calls(telemetry, telemetry_calls) - - def assert_telemetry_call( - self, telemetry_mock, index: int, event_name: str, props: Dict[str, str] - ) -> None: - # pylint: disable=unused-variable - args, kwargs = telemetry_mock.track_event.call_args_list[index] - self.assertEqual(args[0], event_name) - - for key, val in props.items(): - self.assertTrue( - key in args[1], - msg=f"Could not find value {key} in {args[1]} for index {index}", - ) - self.assertTrue(isinstance(args[1], dict)) - self.assertTrue(val == args[1][key]) - - def assert_telemetry_calls(self, telemetry_mock, calls) -> None: - index = 0 - for event_name, props in calls: - self.assert_telemetry_call(telemetry_mock, index, event_name, props) - index += 1 - if index != len(telemetry_mock.track_event.call_args_list): - self.assertTrue( # pylint: disable=redundant-unittest-assert - False, - f"Found {len(telemetry_mock.track_event.call_args_list)} calls, testing for {index + 1}", - ) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from unittest.mock import MagicMock +from typing import Dict +import aiounittest +from botbuilder.core.adapters import TestAdapter, TestFlow +from botbuilder.schema import Activity +from botbuilder.core import ( + ConversationState, + MemoryStorage, + TurnContext, + NullTelemetryClient, +) +from botbuilder.dialogs import ( + Dialog, + DialogSet, + WaterfallDialog, + DialogTurnResult, + DialogTurnStatus, +) + +BEGIN_MESSAGE = Activity() +BEGIN_MESSAGE.text = "begin" +BEGIN_MESSAGE.type = "message" + +MOCK_TELEMETRY = "botbuilder.applicationinsights.ApplicationInsightsTelemetryClient" + + +class TelemetryWaterfallTests(aiounittest.AsyncTestCase): + def test_none_telemetry_client(self): + # arrange + dialog = WaterfallDialog("myId") + # act + dialog.telemetry_client = None + # assert + self.assertEqual(type(dialog.telemetry_client), NullTelemetryClient) + + async def test_execute_sequence_waterfall_steps(self): + # arrange + + # Create new ConversationState with MemoryStorage and register the state as middleware. + convo_state = ConversationState(MemoryStorage()) + telemetry = MagicMock(name=MOCK_TELEMETRY) + + # Create a DialogState property, DialogSet and register the WaterfallDialog. + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + async def step1(step) -> DialogTurnResult: + await step.context.send_activity("bot responding.") + return Dialog.end_of_turn + + async def step2(step) -> DialogTurnResult: + await step.context.send_activity("ending WaterfallDialog.") + return Dialog.end_of_turn + + # act + + my_dialog = WaterfallDialog("test", [step1, step2]) + my_dialog.telemetry_client = telemetry + dialogs.add(my_dialog) + + # Initialize TestAdapter + async def exec_test(turn_context: TurnContext) -> None: + + dialog_context = await dialogs.create_context(turn_context) + results = await dialog_context.continue_dialog() + if results.status == DialogTurnStatus.Empty: + await dialog_context.begin_dialog("test") + else: + if results.status == DialogTurnStatus.Complete: + await turn_context.send_activity(results.result) + + await convo_state.save_changes(turn_context) + + adapt = TestAdapter(exec_test) + + test_flow = TestFlow(None, adapt) + tf2 = await test_flow.send(BEGIN_MESSAGE) + tf3 = await tf2.assert_reply("bot responding.") + tf4 = await tf3.send("continue") + await tf4.assert_reply("ending WaterfallDialog.") + + # assert + + telemetry_calls = [ + ("WaterfallStart", {"DialogId": "test"}), + ("WaterfallStep", {"DialogId": "test", "StepName": "Step1of2"}), + ("WaterfallStep", {"DialogId": "test", "StepName": "Step2of2"}), + ] + self.assert_telemetry_calls(telemetry, telemetry_calls) + + async def test_ensure_end_dialog_called(self): + # arrange + + # Create new ConversationState with MemoryStorage and register the state as middleware. + convo_state = ConversationState(MemoryStorage()) + telemetry = MagicMock(name=MOCK_TELEMETRY) + + # Create a DialogState property, DialogSet and register the WaterfallDialog. + dialog_state = convo_state.create_property("dialogState") + dialogs = DialogSet(dialog_state) + + async def step1(step) -> DialogTurnResult: + await step.context.send_activity("step1 response") + return Dialog.end_of_turn + + async def step2(step) -> DialogTurnResult: + await step.context.send_activity("step2 response") + return Dialog.end_of_turn + + # act + + my_dialog = WaterfallDialog("test", [step1, step2]) + my_dialog.telemetry_client = telemetry + dialogs.add(my_dialog) + + # Initialize TestAdapter + async def exec_test(turn_context: TurnContext) -> None: + + dialog_context = await dialogs.create_context(turn_context) + await dialog_context.continue_dialog() + if not turn_context.responded: + await dialog_context.begin_dialog("test", None) + await convo_state.save_changes(turn_context) + + adapt = TestAdapter(exec_test) + + test_flow = TestFlow(None, adapt) + tf2 = await test_flow.send(BEGIN_MESSAGE) + tf3 = await tf2.assert_reply("step1 response") + tf4 = await tf3.send("continue") + tf5 = await tf4.assert_reply("step2 response") + await tf5.send( + "Should hit end of steps - this will restart the dialog and trigger COMPLETE event" + ) + # assert + telemetry_calls = [ + ("WaterfallStart", {"DialogId": "test"}), + ("WaterfallStep", {"DialogId": "test", "StepName": "Step1of2"}), + ("WaterfallStep", {"DialogId": "test", "StepName": "Step2of2"}), + ("WaterfallComplete", {"DialogId": "test"}), + ("WaterfallStart", {"DialogId": "test"}), + ("WaterfallStep", {"DialogId": "test", "StepName": "Step1of2"}), + ] + print(str(telemetry.track_event.call_args_list)) + self.assert_telemetry_calls(telemetry, telemetry_calls) + + def assert_telemetry_call( + self, telemetry_mock, index: int, event_name: str, props: Dict[str, str] + ) -> None: + # pylint: disable=unused-variable + args, kwargs = telemetry_mock.track_event.call_args_list[index] + self.assertEqual(args[0], event_name) + + for key, val in props.items(): + self.assertTrue( + key in args[1], + msg=f"Could not find value {key} in {args[1]} for index {index}", + ) + self.assertTrue(isinstance(args[1], dict)) + self.assertTrue(val == args[1][key]) + + def assert_telemetry_calls(self, telemetry_mock, calls) -> None: + index = 0 + for event_name, props in calls: + self.assert_telemetry_call(telemetry_mock, index, event_name, props) + index += 1 + if index != len(telemetry_mock.track_event.call_args_list): + self.assertTrue( # pylint: disable=redundant-unittest-assert + False, + f"Found {len(telemetry_mock.track_event.call_args_list)} calls, testing for {index + 1}", + ) diff --git a/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py b/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py --- a/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py +++ b/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py @@ -1,463 +1,467 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -# TODO: enable this in the future -# With python 3.7 the line below will allow to do Postponed Evaluation of Annotations. See PEP 563 -# from __future__ import annotations - -import asyncio -import inspect -from datetime import datetime -from typing import Awaitable, Coroutine, Dict, List, Callable, Union -from copy import copy -from threading import Lock -from botbuilder.schema import ( - ActivityTypes, - Activity, - ConversationAccount, - ConversationReference, - ChannelAccount, - ResourceResponse, - TokenResponse, -) -from botframework.connector.auth import ClaimsIdentity -from ..bot_adapter import BotAdapter -from ..turn_context import TurnContext -from ..user_token_provider import UserTokenProvider - - -class UserToken: - def __init__( - self, - connection_name: str = None, - user_id: str = None, - channel_id: str = None, - token: str = None, - ): - self.connection_name = connection_name - self.user_id = user_id - self.channel_id = channel_id - self.token = token - - def equals_key(self, rhs: "UserToken"): - return ( - rhs is not None - and self.connection_name == rhs.connection_name - and self.user_id == rhs.user_id - and self.channel_id == rhs.channel_id - ) - - -class TokenMagicCode: - def __init__(self, key: UserToken = None, magic_code: str = None): - self.key = key - self.magic_code = magic_code - - -class TestAdapter(BotAdapter, UserTokenProvider): - def __init__( - self, - logic: Coroutine = None, - template_or_conversation: Union[Activity, ConversationReference] = None, - send_trace_activities: bool = False, - ): # pylint: disable=unused-argument - """ - Creates a new TestAdapter instance. - :param logic: - :param conversation: A reference to the conversation to begin the adapter state with. - """ - super(TestAdapter, self).__init__() - self.logic = logic - self._next_id: int = 0 - self._user_tokens: List[UserToken] = [] - self._magic_codes: List[TokenMagicCode] = [] - self._conversation_lock = Lock() - self.activity_buffer: List[Activity] = [] - self.updated_activities: List[Activity] = [] - self.deleted_activities: List[ConversationReference] = [] - self.send_trace_activities = send_trace_activities - - self.template = ( - template_or_conversation - if isinstance(template_or_conversation, Activity) - else Activity( - channel_id="test", - service_url="https://test.com", - from_property=ChannelAccount(id="User1", name="user"), - recipient=ChannelAccount(id="bot", name="Bot"), - conversation=ConversationAccount(id="Convo1"), - ) - ) - - if isinstance(template_or_conversation, ConversationReference): - self.template.channel_id = template_or_conversation.channel_id - - async def process_activity( - self, activity: Activity, logic: Callable[[TurnContext], Awaitable] - ): - self._conversation_lock.acquire() - try: - # ready for next reply - if activity.type is None: - activity.type = ActivityTypes.message - - activity.channel_id = self.template.channel_id - activity.from_property = self.template.from_property - activity.recipient = self.template.recipient - activity.conversation = self.template.conversation - activity.service_url = self.template.service_url - - activity.id = str((self._next_id)) - self._next_id += 1 - finally: - self._conversation_lock.release() - - activity.timestamp = activity.timestamp or datetime.utcnow() - await self.run_pipeline(TurnContext(self, activity), logic) - - async def send_activities( - self, context, activities: List[Activity] - ) -> List[ResourceResponse]: - """ - INTERNAL: called by the logic under test to send a set of activities. These will be buffered - to the current `TestFlow` instance for comparison against the expected results. - :param context: - :param activities: - :return: - """ - - def id_mapper(activity): - self.activity_buffer.append(activity) - self._next_id += 1 - return ResourceResponse(id=str(self._next_id)) - - return [ - id_mapper(activity) - for activity in activities - if self.send_trace_activities or activity.type != "trace" - ] - - async def delete_activity(self, context, reference: ConversationReference): - """ - INTERNAL: called by the logic under test to delete an existing activity. These are simply - pushed onto a [deletedActivities](#deletedactivities) array for inspection after the turn - completes. - :param reference: - :return: - """ - self.deleted_activities.append(reference) - - async def update_activity(self, context, activity: Activity): - """ - INTERNAL: called by the logic under test to replace an existing activity. These are simply - pushed onto an [updatedActivities](#updatedactivities) array for inspection after the turn - completes. - :param activity: - :return: - """ - self.updated_activities.append(activity) - - async def continue_conversation( - self, - reference: ConversationReference, - callback: Callable, - bot_id: str = None, - claims_identity: ClaimsIdentity = None, # pylint: disable=unused-argument - ): - """ - The `TestAdapter` just calls parent implementation. - :param reference: - :param callback: - :param bot_id: - :param claims_identity: - :return: - """ - await super().continue_conversation( - reference, callback, bot_id, claims_identity - ) - - async def receive_activity(self, activity): - """ - INTERNAL: called by a `TestFlow` instance to simulate a user sending a message to the bot. - This will cause the adapters middleware pipe to be run and it's logic to be called. - :param activity: - :return: - """ - if isinstance(activity, str): - activity = Activity(type="message", text=activity) - # Initialize request. - request = copy(self.template) - - for key, value in vars(activity).items(): - if value is not None and key != "additional_properties": - setattr(request, key, value) - - request.type = request.type or ActivityTypes.message - if not request.id: - self._next_id += 1 - request.id = str(self._next_id) - - # Create context object and run middleware. - context = TurnContext(self, request) - return await self.run_pipeline(context, self.logic) - - def get_next_activity(self) -> Activity: - return self.activity_buffer.pop(0) - - async def send(self, user_says) -> object: - """ - Sends something to the bot. This returns a new `TestFlow` instance which can be used to add - additional steps for inspecting the bots reply and then sending additional activities. - :param user_says: - :return: A new instance of the TestFlow object - """ - return TestFlow(await self.receive_activity(user_says), self) - - async def test( - self, user_says, expected, description=None, timeout=None - ) -> "TestFlow": - """ - Send something to the bot and expects the bot to return with a given reply. This is simply a - wrapper around calls to `send()` and `assertReply()`. This is such a common pattern that a - helper is provided. - :param user_says: - :param expected: - :param description: - :param timeout: - :return: - """ - test_flow = await self.send(user_says) - test_flow = await test_flow.assert_reply(expected, description, timeout) - return test_flow - - async def tests(self, *args): - """ - Support multiple test cases without having to manually call `test()` repeatedly. This is a - convenience layer around the `test()`. Valid args are either lists or tuples of parameters - :param args: - :return: - """ - for arg in args: - description = None - timeout = None - if len(arg) >= 3: - description = arg[2] - if len(arg) == 4: - timeout = arg[3] - await self.test(arg[0], arg[1], description, timeout) - - def add_user_token( - self, - connection_name: str, - channel_id: str, - user_id: str, - token: str, - magic_code: str = None, - ): - key = UserToken() - key.channel_id = channel_id - key.connection_name = connection_name - key.user_id = user_id - key.token = token - - if not magic_code: - self._user_tokens.append(key) - else: - code = TokenMagicCode() - code.key = key - code.magic_code = magic_code - self._magic_codes.append(code) - - async def get_user_token( - self, context: TurnContext, connection_name: str, magic_code: str = None - ) -> TokenResponse: - key = UserToken() - key.channel_id = context.activity.channel_id - key.connection_name = connection_name - key.user_id = context.activity.from_property.id - - if magic_code: - magic_code_record = list( - filter(lambda x: key.equals_key(x.key), self._magic_codes) - ) - if magic_code_record and magic_code_record[0].magic_code == magic_code: - # Move the token to long term dictionary. - self.add_user_token( - connection_name, - key.channel_id, - key.user_id, - magic_code_record[0].key.token, - ) - - # Remove from the magic code list. - idx = self._magic_codes.index(magic_code_record[0]) - self._magic_codes = [self._magic_codes.pop(idx)] - - match = [token for token in self._user_tokens if key.equals_key(token)] - - if match: - return TokenResponse( - connection_name=match[0].connection_name, - token=match[0].token, - expiration=None, - ) - # Not found. - return None - - async def sign_out_user( - self, context: TurnContext, connection_name: str, user_id: str = None - ): - channel_id = context.activity.channel_id - user_id = context.activity.from_property.id - - new_records = [] - for token in self._user_tokens: - if ( - token.channel_id != channel_id - or token.user_id != user_id - or (connection_name and connection_name != token.connection_name) - ): - new_records.append(token) - self._user_tokens = new_records - - async def get_oauth_sign_in_link( - self, context: TurnContext, connection_name: str - ) -> str: - return ( - f"https://fake.com/oauthsignin" - f"/{connection_name}/{context.activity.channel_id}/{context.activity.from_property.id}" - ) - - async def get_aad_tokens( - self, context: TurnContext, connection_name: str, resource_urls: List[str] - ) -> Dict[str, TokenResponse]: - return None - - -class TestFlow: - def __init__(self, previous: Callable, adapter: TestAdapter): - """ - INTERNAL: creates a new TestFlow instance. - :param previous: - :param adapter: - """ - self.previous = previous - self.adapter = adapter - - async def test( - self, user_says, expected, description=None, timeout=None - ) -> "TestFlow": - """ - Send something to the bot and expects the bot to return with a given reply. This is simply a - wrapper around calls to `send()` and `assertReply()`. This is such a common pattern that a - helper is provided. - :param user_says: - :param expected: - :param description: - :param timeout: - :return: - """ - test_flow = await self.send(user_says) - return await test_flow.assert_reply( - expected, description or f'test("{user_says}", "{expected}")', timeout - ) - - async def send(self, user_says) -> "TestFlow": - """ - Sends something to the bot. - :param user_says: - :return: - """ - - async def new_previous(): - nonlocal self, user_says - if callable(self.previous): - await self.previous() - await self.adapter.receive_activity(user_says) - - return TestFlow(await new_previous(), self.adapter) - - async def assert_reply( - self, - expected: Union[str, Activity, Callable[[Activity, str], None]], - description=None, - timeout=None, # pylint: disable=unused-argument - is_substring=False, - ) -> "TestFlow": - """ - Generates an assertion if the bots response doesn't match the expected text/activity. - :param expected: - :param description: - :param timeout: - :param is_substring: - :return: - """ - # TODO: refactor method so expected can take a Callable[[Activity], None] - def default_inspector(reply, description=None): - if isinstance(expected, Activity): - validate_activity(reply, expected) - else: - assert reply.type == "message", description + f" type == {reply.type}" - if is_substring: - assert expected in reply.text.strip(), ( - description + f" text == {reply.text}" - ) - else: - assert reply.text.strip() == expected.strip(), ( - description + f" text == {reply.text}" - ) - - if description is None: - description = "" - - inspector = expected if callable(expected) else default_inspector - - async def test_flow_previous(): - nonlocal timeout - if not timeout: - timeout = 3000 - start = datetime.now() - adapter = self.adapter - - async def wait_for_activity(): - nonlocal expected, timeout - current = datetime.now() - if (current - start).total_seconds() * 1000 > timeout: - if isinstance(expected, Activity): - expecting = expected.text - elif callable(expected): - expecting = inspect.getsourcefile(expected) - else: - expecting = str(expected) - raise RuntimeError( - f"TestAdapter.assert_reply({expecting}): {description} Timed out after " - f"{current - start}ms." - ) - if adapter.activity_buffer: - reply = adapter.activity_buffer.pop(0) - try: - await inspector(reply, description) - except Exception: - inspector(reply, description) - - else: - await asyncio.sleep(0.05) - await wait_for_activity() - - await wait_for_activity() - - return TestFlow(await test_flow_previous(), self.adapter) - - -def validate_activity(activity, expected) -> None: - """ - Helper method that compares activities - :param activity: - :param expected: - :return: - """ - iterable_expected = vars(expected).items() - - for attr, value in iterable_expected: - if value is not None and attr != "additional_properties": - assert value == getattr(activity, attr) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +# TODO: enable this in the future +# With python 3.7 the line below will allow to do Postponed Evaluation of Annotations. See PEP 563 +# from __future__ import annotations + +import asyncio +import inspect +from datetime import datetime +from typing import Awaitable, Coroutine, Dict, List, Callable, Union +from copy import copy +from threading import Lock +from botbuilder.schema import ( + ActivityTypes, + Activity, + ConversationAccount, + ConversationReference, + ChannelAccount, + ResourceResponse, + TokenResponse, +) +from botframework.connector.auth import ClaimsIdentity +from ..bot_adapter import BotAdapter +from ..turn_context import TurnContext +from ..user_token_provider import UserTokenProvider + + +class UserToken: + def __init__( + self, + connection_name: str = None, + user_id: str = None, + channel_id: str = None, + token: str = None, + ): + self.connection_name = connection_name + self.user_id = user_id + self.channel_id = channel_id + self.token = token + + def equals_key(self, rhs: "UserToken"): + return ( + rhs is not None + and self.connection_name == rhs.connection_name + and self.user_id == rhs.user_id + and self.channel_id == rhs.channel_id + ) + + +class TokenMagicCode: + def __init__(self, key: UserToken = None, magic_code: str = None): + self.key = key + self.magic_code = magic_code + + +class TestAdapter(BotAdapter, UserTokenProvider): + __test__ = False + + def __init__( + self, + logic: Coroutine = None, + template_or_conversation: Union[Activity, ConversationReference] = None, + send_trace_activities: bool = False, + ): # pylint: disable=unused-argument + """ + Creates a new TestAdapter instance. + :param logic: + :param conversation: A reference to the conversation to begin the adapter state with. + """ + super(TestAdapter, self).__init__() + self.logic = logic + self._next_id: int = 0 + self._user_tokens: List[UserToken] = [] + self._magic_codes: List[TokenMagicCode] = [] + self._conversation_lock = Lock() + self.activity_buffer: List[Activity] = [] + self.updated_activities: List[Activity] = [] + self.deleted_activities: List[ConversationReference] = [] + self.send_trace_activities = send_trace_activities + + self.template = ( + template_or_conversation + if isinstance(template_or_conversation, Activity) + else Activity( + channel_id="test", + service_url="https://test.com", + from_property=ChannelAccount(id="User1", name="user"), + recipient=ChannelAccount(id="bot", name="Bot"), + conversation=ConversationAccount(id="Convo1"), + ) + ) + + if isinstance(template_or_conversation, ConversationReference): + self.template.channel_id = template_or_conversation.channel_id + + async def process_activity( + self, activity: Activity, logic: Callable[[TurnContext], Awaitable] + ): + self._conversation_lock.acquire() + try: + # ready for next reply + if activity.type is None: + activity.type = ActivityTypes.message + + activity.channel_id = self.template.channel_id + activity.from_property = self.template.from_property + activity.recipient = self.template.recipient + activity.conversation = self.template.conversation + activity.service_url = self.template.service_url + + activity.id = str((self._next_id)) + self._next_id += 1 + finally: + self._conversation_lock.release() + + activity.timestamp = activity.timestamp or datetime.utcnow() + await self.run_pipeline(TurnContext(self, activity), logic) + + async def send_activities( + self, context, activities: List[Activity] + ) -> List[ResourceResponse]: + """ + INTERNAL: called by the logic under test to send a set of activities. These will be buffered + to the current `TestFlow` instance for comparison against the expected results. + :param context: + :param activities: + :return: + """ + + def id_mapper(activity): + self.activity_buffer.append(activity) + self._next_id += 1 + return ResourceResponse(id=str(self._next_id)) + + return [ + id_mapper(activity) + for activity in activities + if self.send_trace_activities or activity.type != "trace" + ] + + async def delete_activity(self, context, reference: ConversationReference): + """ + INTERNAL: called by the logic under test to delete an existing activity. These are simply + pushed onto a [deletedActivities](#deletedactivities) array for inspection after the turn + completes. + :param reference: + :return: + """ + self.deleted_activities.append(reference) + + async def update_activity(self, context, activity: Activity): + """ + INTERNAL: called by the logic under test to replace an existing activity. These are simply + pushed onto an [updatedActivities](#updatedactivities) array for inspection after the turn + completes. + :param activity: + :return: + """ + self.updated_activities.append(activity) + + async def continue_conversation( + self, + reference: ConversationReference, + callback: Callable, + bot_id: str = None, + claims_identity: ClaimsIdentity = None, # pylint: disable=unused-argument + ): + """ + The `TestAdapter` just calls parent implementation. + :param reference: + :param callback: + :param bot_id: + :param claims_identity: + :return: + """ + await super().continue_conversation( + reference, callback, bot_id, claims_identity + ) + + async def receive_activity(self, activity): + """ + INTERNAL: called by a `TestFlow` instance to simulate a user sending a message to the bot. + This will cause the adapters middleware pipe to be run and it's logic to be called. + :param activity: + :return: + """ + if isinstance(activity, str): + activity = Activity(type="message", text=activity) + # Initialize request. + request = copy(self.template) + + for key, value in vars(activity).items(): + if value is not None and key != "additional_properties": + setattr(request, key, value) + + request.type = request.type or ActivityTypes.message + if not request.id: + self._next_id += 1 + request.id = str(self._next_id) + + # Create context object and run middleware. + context = TurnContext(self, request) + return await self.run_pipeline(context, self.logic) + + def get_next_activity(self) -> Activity: + return self.activity_buffer.pop(0) + + async def send(self, user_says) -> object: + """ + Sends something to the bot. This returns a new `TestFlow` instance which can be used to add + additional steps for inspecting the bots reply and then sending additional activities. + :param user_says: + :return: A new instance of the TestFlow object + """ + return TestFlow(await self.receive_activity(user_says), self) + + async def test( + self, user_says, expected, description=None, timeout=None + ) -> "TestFlow": + """ + Send something to the bot and expects the bot to return with a given reply. This is simply a + wrapper around calls to `send()` and `assertReply()`. This is such a common pattern that a + helper is provided. + :param user_says: + :param expected: + :param description: + :param timeout: + :return: + """ + test_flow = await self.send(user_says) + test_flow = await test_flow.assert_reply(expected, description, timeout) + return test_flow + + async def tests(self, *args): + """ + Support multiple test cases without having to manually call `test()` repeatedly. This is a + convenience layer around the `test()`. Valid args are either lists or tuples of parameters + :param args: + :return: + """ + for arg in args: + description = None + timeout = None + if len(arg) >= 3: + description = arg[2] + if len(arg) == 4: + timeout = arg[3] + await self.test(arg[0], arg[1], description, timeout) + + def add_user_token( + self, + connection_name: str, + channel_id: str, + user_id: str, + token: str, + magic_code: str = None, + ): + key = UserToken() + key.channel_id = channel_id + key.connection_name = connection_name + key.user_id = user_id + key.token = token + + if not magic_code: + self._user_tokens.append(key) + else: + code = TokenMagicCode() + code.key = key + code.magic_code = magic_code + self._magic_codes.append(code) + + async def get_user_token( + self, context: TurnContext, connection_name: str, magic_code: str = None + ) -> TokenResponse: + key = UserToken() + key.channel_id = context.activity.channel_id + key.connection_name = connection_name + key.user_id = context.activity.from_property.id + + if magic_code: + magic_code_record = list( + filter(lambda x: key.equals_key(x.key), self._magic_codes) + ) + if magic_code_record and magic_code_record[0].magic_code == magic_code: + # Move the token to long term dictionary. + self.add_user_token( + connection_name, + key.channel_id, + key.user_id, + magic_code_record[0].key.token, + ) + + # Remove from the magic code list. + idx = self._magic_codes.index(magic_code_record[0]) + self._magic_codes = [self._magic_codes.pop(idx)] + + match = [token for token in self._user_tokens if key.equals_key(token)] + + if match: + return TokenResponse( + connection_name=match[0].connection_name, + token=match[0].token, + expiration=None, + ) + # Not found. + return None + + async def sign_out_user( + self, context: TurnContext, connection_name: str, user_id: str = None + ): + channel_id = context.activity.channel_id + user_id = context.activity.from_property.id + + new_records = [] + for token in self._user_tokens: + if ( + token.channel_id != channel_id + or token.user_id != user_id + or (connection_name and connection_name != token.connection_name) + ): + new_records.append(token) + self._user_tokens = new_records + + async def get_oauth_sign_in_link( + self, context: TurnContext, connection_name: str + ) -> str: + return ( + f"https://fake.com/oauthsignin" + f"/{connection_name}/{context.activity.channel_id}/{context.activity.from_property.id}" + ) + + async def get_aad_tokens( + self, context: TurnContext, connection_name: str, resource_urls: List[str] + ) -> Dict[str, TokenResponse]: + return None + + +class TestFlow: + __test__ = False + + def __init__(self, previous: Callable, adapter: TestAdapter): + """ + INTERNAL: creates a new TestFlow instance. + :param previous: + :param adapter: + """ + self.previous = previous + self.adapter = adapter + + async def test( + self, user_says, expected, description=None, timeout=None + ) -> "TestFlow": + """ + Send something to the bot and expects the bot to return with a given reply. This is simply a + wrapper around calls to `send()` and `assertReply()`. This is such a common pattern that a + helper is provided. + :param user_says: + :param expected: + :param description: + :param timeout: + :return: + """ + test_flow = await self.send(user_says) + return await test_flow.assert_reply( + expected, description or f'test("{user_says}", "{expected}")', timeout + ) + + async def send(self, user_says) -> "TestFlow": + """ + Sends something to the bot. + :param user_says: + :return: + """ + + async def new_previous(): + nonlocal self, user_says + if callable(self.previous): + await self.previous() + await self.adapter.receive_activity(user_says) + + return TestFlow(await new_previous(), self.adapter) + + async def assert_reply( + self, + expected: Union[str, Activity, Callable[[Activity, str], None]], + description=None, + timeout=None, # pylint: disable=unused-argument + is_substring=False, + ) -> "TestFlow": + """ + Generates an assertion if the bots response doesn't match the expected text/activity. + :param expected: + :param description: + :param timeout: + :param is_substring: + :return: + """ + # TODO: refactor method so expected can take a Callable[[Activity], None] + def default_inspector(reply, description=None): + if isinstance(expected, Activity): + validate_activity(reply, expected) + else: + assert reply.type == "message", description + f" type == {reply.type}" + if is_substring: + assert expected in reply.text.strip(), ( + description + f" text == {reply.text}" + ) + else: + assert reply.text.strip() == expected.strip(), ( + description + f" text == {reply.text}" + ) + + if description is None: + description = "" + + inspector = expected if callable(expected) else default_inspector + + async def test_flow_previous(): + nonlocal timeout + if not timeout: + timeout = 3000 + start = datetime.now() + adapter = self.adapter + + async def wait_for_activity(): + nonlocal expected, timeout + current = datetime.now() + if (current - start).total_seconds() * 1000 > timeout: + if isinstance(expected, Activity): + expecting = expected.text + elif callable(expected): + expecting = inspect.getsourcefile(expected) + else: + expecting = str(expected) + raise RuntimeError( + f"TestAdapter.assert_reply({expecting}): {description} Timed out after " + f"{current - start}ms." + ) + if adapter.activity_buffer: + reply = adapter.activity_buffer.pop(0) + try: + await inspector(reply, description) + except Exception: + inspector(reply, description) + + else: + await asyncio.sleep(0.05) + await wait_for_activity() + + await wait_for_activity() + + return TestFlow(await test_flow_previous(), self.adapter) + + +def validate_activity(activity, expected) -> None: + """ + Helper method that compares activities + :param activity: + :param expected: + :return: + """ + iterable_expected = vars(expected).items() + + for attr, value in iterable_expected: + if value is not None and attr != "additional_properties": + assert value == getattr(activity, attr) diff --git a/libraries/botbuilder-core/tests/simple_adapter.py b/libraries/botbuilder-core/tests/simple_adapter.py --- a/libraries/botbuilder-core/tests/simple_adapter.py +++ b/libraries/botbuilder-core/tests/simple_adapter.py @@ -1,60 +1,60 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -import unittest -from typing import List -from botbuilder.core import BotAdapter, TurnContext -from botbuilder.schema import Activity, ConversationReference, ResourceResponse - - -class SimpleAdapter(BotAdapter): - # pylint: disable=unused-argument - - def __init__(self, call_on_send=None, call_on_update=None, call_on_delete=None): - super(SimpleAdapter, self).__init__() - self.test_aux = unittest.TestCase("__init__") - self._call_on_send = call_on_send - self._call_on_update = call_on_update - self._call_on_delete = call_on_delete - - async def delete_activity( - self, context: TurnContext, reference: ConversationReference - ): - self.test_aux.assertIsNotNone( - reference, "SimpleAdapter.delete_activity: missing reference" - ) - if self._call_on_delete is not None: - self._call_on_delete(reference) - - async def send_activities( - self, context: TurnContext, activities: List[Activity] - ) -> List[ResourceResponse]: - self.test_aux.assertIsNotNone( - activities, "SimpleAdapter.delete_activity: missing reference" - ) - self.test_aux.assertTrue( - len(activities) > 0, - "SimpleAdapter.send_activities: empty activities array.", - ) - - if self._call_on_send is not None: - self._call_on_send(activities) - responses = [] - - for activity in activities: - responses.append(ResourceResponse(id=activity.id)) - - return responses - - async def update_activity(self, context: TurnContext, activity: Activity): - self.test_aux.assertIsNotNone( - activity, "SimpleAdapter.update_activity: missing activity" - ) - if self._call_on_update is not None: - self._call_on_update(activity) - - return ResourceResponse(activity.id) - - async def process_request(self, activity, handler): - context = TurnContext(self, activity) - return self.run_pipeline(context, handler) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import unittest +from typing import List +from botbuilder.core import BotAdapter, TurnContext +from botbuilder.schema import Activity, ConversationReference, ResourceResponse + + +class SimpleAdapter(BotAdapter): + # pylint: disable=unused-argument + + def __init__(self, call_on_send=None, call_on_update=None, call_on_delete=None): + super(SimpleAdapter, self).__init__() + self.test_aux = unittest.TestCase("__init__") + self._call_on_send = call_on_send + self._call_on_update = call_on_update + self._call_on_delete = call_on_delete + + async def delete_activity( + self, context: TurnContext, reference: ConversationReference + ): + self.test_aux.assertIsNotNone( + reference, "SimpleAdapter.delete_activity: missing reference" + ) + if self._call_on_delete is not None: + self._call_on_delete(reference) + + async def send_activities( + self, context: TurnContext, activities: List[Activity] + ) -> List[ResourceResponse]: + self.test_aux.assertIsNotNone( + activities, "SimpleAdapter.delete_activity: missing reference" + ) + self.test_aux.assertTrue( + len(activities) > 0, + "SimpleAdapter.send_activities: empty activities array.", + ) + + if self._call_on_send is not None: + self._call_on_send(activities) + responses = [] + + for activity in activities: + responses.append(ResourceResponse(id=activity.id)) + + return responses + + async def update_activity(self, context: TurnContext, activity: Activity): + self.test_aux.assertIsNotNone( + activity, "SimpleAdapter.update_activity: missing activity" + ) + if self._call_on_update is not None: + self._call_on_update(activity) + + return ResourceResponse(activity.id) + + async def process_request(self, activity, handler): + context = TurnContext(self, activity) + return await self.run_pipeline(context, handler) diff --git a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py --- a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py +++ b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py @@ -1,724 +1,726 @@ -from typing import List - -import aiounittest -from botbuilder.core import BotAdapter, TurnContext -from botbuilder.core.teams import TeamsActivityHandler -from botbuilder.schema import ( - Activity, - ActivityTypes, - ChannelAccount, - ConversationReference, - ResourceResponse, -) -from botbuilder.schema.teams import ( - AppBasedLinkQuery, - ChannelInfo, - FileConsentCardResponse, - MessageActionsPayload, - MessagingExtensionAction, - MessagingExtensionQuery, - O365ConnectorCardActionQuery, - TaskModuleRequest, - TaskModuleRequestContext, - TeamInfo, - TeamsChannelAccount, -) -from botframework.connector import Channels -from simple_adapter import SimpleAdapter - - -class TestingTeamsActivityHandler(TeamsActivityHandler): - def __init__(self): - self.record: List[str] = [] - - async def on_conversation_update_activity(self, turn_context: TurnContext): - self.record.append("on_conversation_update_activity") - return await super().on_conversation_update_activity(turn_context) - - async def on_teams_members_removed( - self, teams_members_removed: [TeamsChannelAccount], turn_context: TurnContext - ): - self.record.append("on_teams_members_removed") - return await super().on_teams_members_removed( - teams_members_removed, turn_context - ) - - async def on_message_activity(self, turn_context: TurnContext): - self.record.append("on_message_activity") - return await super().on_message_activity(turn_context) - - async def on_token_response_event(self, turn_context: TurnContext): - self.record.append("on_token_response_event") - return await super().on_token_response_event(turn_context) - - async def on_event(self, turn_context: TurnContext): - self.record.append("on_event") - return await super().on_event(turn_context) - - async def on_unrecognized_activity_type(self, turn_context: TurnContext): - self.record.append("on_unrecognized_activity_type") - return await super().on_unrecognized_activity_type(turn_context) - - async def on_teams_channel_created( - self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext - ): - self.record.append("on_teams_channel_created") - return await super().on_teams_channel_created( - channel_info, team_info, turn_context - ) - - async def on_teams_channel_renamed( - self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext - ): - self.record.append("on_teams_channel_renamed") - return await super().on_teams_channel_renamed( - channel_info, team_info, turn_context - ) - - async def on_teams_channel_deleted( - self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext - ): - self.record.append("on_teams_channel_deleted") - return await super().on_teams_channel_renamed( - channel_info, team_info, turn_context - ) - - async def on_teams_team_renamed_activity( - self, team_info: TeamInfo, turn_context: TurnContext - ): - self.record.append("on_teams_team_renamed_activity") - return await super().on_teams_team_renamed_activity(team_info, turn_context) - - async def on_invoke_activity(self, turn_context: TurnContext): - self.record.append("on_invoke_activity") - return await super().on_invoke_activity(turn_context) - - async def on_teams_signin_verify_state(self, turn_context: TurnContext): - self.record.append("on_teams_signin_verify_state") - return await super().on_teams_signin_verify_state(turn_context) - - async def on_teams_file_consent( - self, - turn_context: TurnContext, - file_consent_card_response: FileConsentCardResponse, - ): - self.record.append("on_teams_file_consent") - return await super().on_teams_file_consent( - turn_context, file_consent_card_response - ) - - async def on_teams_file_consent_accept( - self, - turn_context: TurnContext, - file_consent_card_response: FileConsentCardResponse, - ): - self.record.append("on_teams_file_consent_accept") - return await super().on_teams_file_consent_accept( - turn_context, file_consent_card_response - ) - - async def on_teams_file_consent_decline( - self, - turn_context: TurnContext, - file_consent_card_response: FileConsentCardResponse, - ): - self.record.append("on_teams_file_consent_decline") - return await super().on_teams_file_consent_decline( - turn_context, file_consent_card_response - ) - - async def on_teams_o365_connector_card_action( - self, turn_context: TurnContext, query: O365ConnectorCardActionQuery - ): - self.record.append("on_teams_o365_connector_card_action") - return await super().on_teams_o365_connector_card_action(turn_context, query) - - async def on_teams_app_based_link_query( - self, turn_context: TurnContext, query: AppBasedLinkQuery - ): - self.record.append("on_teams_app_based_link_query") - return await super().on_teams_app_based_link_query(turn_context, query) - - async def on_teams_messaging_extension_query( - self, turn_context: TurnContext, query: MessagingExtensionQuery - ): - self.record.append("on_teams_messaging_extension_query") - return await super().on_teams_messaging_extension_query(turn_context, query) - - async def on_teams_messaging_extension_submit_action_dispatch( - self, turn_context: TurnContext, action: MessagingExtensionAction - ): - self.record.append("on_teams_messaging_extension_submit_action_dispatch") - return await super().on_teams_messaging_extension_submit_action_dispatch( - turn_context, action - ) - - async def on_teams_messaging_extension_submit_action( - self, turn_context: TurnContext, action: MessagingExtensionAction - ): - self.record.append("on_teams_messaging_extension_submit_action") - return await super().on_teams_messaging_extension_submit_action( - turn_context, action - ) - - async def on_teams_messaging_extension_bot_message_preview_edit( - self, turn_context: TurnContext, action: MessagingExtensionAction - ): - self.record.append("on_teams_messaging_extension_bot_message_preview_edit") - return await super().on_teams_messaging_extension_bot_message_preview_edit( - turn_context, action - ) - - async def on_teams_messaging_extension_bot_message_preview_send( - self, turn_context: TurnContext, action: MessagingExtensionAction - ): - self.record.append("on_teams_messaging_extension_bot_message_preview_send") - return await super().on_teams_messaging_extension_bot_message_preview_send( - turn_context, action - ) - - async def on_teams_messaging_extension_fetch_task( - self, turn_context: TurnContext, action: MessagingExtensionAction - ): - self.record.append("on_teams_messaging_extension_fetch_task") - return await super().on_teams_messaging_extension_fetch_task( - turn_context, action - ) - - async def on_teams_messaging_extension_configuration_query_settings_url( - self, turn_context: TurnContext, query: MessagingExtensionQuery - ): - self.record.append( - "on_teams_messaging_extension_configuration_query_settings_url" - ) - return await super().on_teams_messaging_extension_configuration_query_settings_url( - turn_context, query - ) - - async def on_teams_messaging_extension_configuration_setting( - self, turn_context: TurnContext, settings - ): - self.record.append("on_teams_messaging_extension_configuration_setting") - return await super().on_teams_messaging_extension_configuration_setting( - turn_context, settings - ) - - async def on_teams_messaging_extension_card_button_clicked( - self, turn_context: TurnContext, card_data - ): - self.record.append("on_teams_messaging_extension_card_button_clicked") - return await super().on_teams_messaging_extension_card_button_clicked( - turn_context, card_data - ) - - async def on_teams_task_module_fetch( - self, turn_context: TurnContext, task_module_request - ): - self.record.append("on_teams_task_module_fetch") - return await super().on_teams_task_module_fetch( - turn_context, task_module_request - ) - - async def on_teams_task_module_submit( # pylint: disable=unused-argument - self, turn_context: TurnContext, task_module_request: TaskModuleRequest - ): - self.record.append("on_teams_task_module_submit") - return await super().on_teams_task_module_submit( - turn_context, task_module_request - ) - - -class NotImplementedAdapter(BotAdapter): - async def delete_activity( - self, context: TurnContext, reference: ConversationReference - ): - raise NotImplementedError() - - async def send_activities( - self, context: TurnContext, activities: List[Activity] - ) -> List[ResourceResponse]: - raise NotImplementedError() - - async def update_activity(self, context: TurnContext, activity: Activity): - raise NotImplementedError() - - -class TestTeamsActivityHandler(aiounittest.AsyncTestCase): - async def test_on_teams_channel_created_activity(self): - # arrange - activity = Activity( - type=ActivityTypes.conversation_update, - channel_data={ - "eventType": "channelCreated", - "channel": {"id": "asdfqwerty", "name": "new_channel"}, - }, - channel_id=Channels.ms_teams, - ) - - turn_context = TurnContext(NotImplementedAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_conversation_update_activity" - assert bot.record[1] == "on_teams_channel_created" - - async def test_on_teams_channel_renamed_activity(self): - # arrange - activity = Activity( - type=ActivityTypes.conversation_update, - channel_data={ - "eventType": "channelRenamed", - "channel": {"id": "asdfqwerty", "name": "new_channel"}, - }, - channel_id=Channels.ms_teams, - ) - - turn_context = TurnContext(NotImplementedAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_conversation_update_activity" - assert bot.record[1] == "on_teams_channel_renamed" - - async def test_on_teams_channel_deleted_activity(self): - # arrange - activity = Activity( - type=ActivityTypes.conversation_update, - channel_data={ - "eventType": "channelDeleted", - "channel": {"id": "asdfqwerty", "name": "new_channel"}, - }, - channel_id=Channels.ms_teams, - ) - - turn_context = TurnContext(NotImplementedAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_conversation_update_activity" - assert bot.record[1] == "on_teams_channel_deleted" - - async def test_on_teams_team_renamed_activity(self): - # arrange - activity = Activity( - type=ActivityTypes.conversation_update, - channel_data={ - "eventType": "teamRenamed", - "team": {"id": "team_id_1", "name": "new_team_name"}, - }, - channel_id=Channels.ms_teams, - ) - - turn_context = TurnContext(NotImplementedAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_conversation_update_activity" - assert bot.record[1] == "on_teams_team_renamed_activity" - - async def test_on_teams_members_removed_activity(self): - # arrange - activity = Activity( - type=ActivityTypes.conversation_update, - channel_data={"eventType": "teamMemberRemoved"}, - members_removed=[ - ChannelAccount( - id="123", - name="test_user", - aad_object_id="asdfqwerty", - role="tester", - ) - ], - channel_id=Channels.ms_teams, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_conversation_update_activity" - assert bot.record[1] == "on_teams_members_removed" - - async def test_on_signin_verify_state(self): - # arrange - activity = Activity(type=ActivityTypes.invoke, name="signin/verifyState") - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_signin_verify_state" - - async def test_on_file_consent_accept_activity(self): - # arrange - activity = Activity( - type=ActivityTypes.invoke, - name="fileConsent/invoke", - value={"action": "accept"}, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 3 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_file_consent" - assert bot.record[2] == "on_teams_file_consent_accept" - - async def test_on_file_consent_decline_activity(self): - # Arrange - activity = Activity( - type=ActivityTypes.invoke, - name="fileConsent/invoke", - value={"action": "decline"}, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 3 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_file_consent" - assert bot.record[2] == "on_teams_file_consent_decline" - - async def test_on_file_consent_bad_action_activity(self): - # Arrange - activity = Activity( - type=ActivityTypes.invoke, - name="fileConsent/invoke", - value={"action": "bad_action"}, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_file_consent" - - async def test_on_teams_o365_connector_card_action(self): - # arrange - activity = Activity( - type=ActivityTypes.invoke, - name="actionableMessage/executeAction", - value={"body": "body_here", "actionId": "action_id_here"}, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_o365_connector_card_action" - - async def test_on_app_based_link_query(self): - # arrange - activity = Activity( - type=ActivityTypes.invoke, - name="composeExtension/query", - value={"url": "http://www.test.com"}, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_messaging_extension_query" - - async def test_on_teams_messaging_extension_bot_message_preview_edit_activity(self): - # Arrange - - activity = Activity( - type=ActivityTypes.invoke, - name="composeExtension/submitAction", - value={ - "data": {"key": "value"}, - "context": {"theme": "dark"}, - "commandId": "test_command", - "commandContext": "command_context_test", - "botMessagePreviewAction": "edit", - "botActivityPreview": [{"id": "activity123"}], - "messagePayload": {"id": "payloadid"}, - }, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 3 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_messaging_extension_submit_action_dispatch" - assert bot.record[2] == "on_teams_messaging_extension_bot_message_preview_edit" - - async def test_on_teams_messaging_extension_bot_message_send_activity(self): - # Arrange - activity = Activity( - type=ActivityTypes.invoke, - name="composeExtension/submitAction", - value={ - "data": {"key": "value"}, - "context": {"theme": "dark"}, - "commandId": "test_command", - "commandContext": "command_context_test", - "botMessagePreviewAction": "send", - "botActivityPreview": [{"id": "123"}], - "messagePayload": {"id": "abc"}, - }, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 3 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_messaging_extension_submit_action_dispatch" - assert bot.record[2] == "on_teams_messaging_extension_bot_message_preview_send" - - async def test_on_teams_messaging_extension_bot_message_send_activity_with_none( - self, - ): - # Arrange - activity = Activity( - type=ActivityTypes.invoke, - name="composeExtension/submitAction", - value={ - "data": {"key": "value"}, - "context": {"theme": "dark"}, - "commandId": "test_command", - "commandContext": "command_context_test", - "botMessagePreviewAction": None, - "botActivityPreview": [{"id": "test123"}], - "messagePayload": {"id": "payloadid123"}, - }, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 3 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_messaging_extension_submit_action_dispatch" - assert bot.record[2] == "on_teams_messaging_extension_submit_action" - - async def test_on_teams_messaging_extension_bot_message_send_activity_with_empty_string( - self, - ): - # Arrange - activity = Activity( - type=ActivityTypes.invoke, - name="composeExtension/submitAction", - value={ - "data": {"key": "value"}, - "context": {"theme": "dark"}, - "commandId": "test_command", - "commandContext": "command_context_test", - "botMessagePreviewAction": "", - "botActivityPreview": [Activity().serialize()], - "messagePayload": MessageActionsPayload().serialize(), - }, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 3 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_messaging_extension_submit_action_dispatch" - assert bot.record[2] == "on_teams_messaging_extension_submit_action" - - async def test_on_teams_messaging_extension_fetch_task(self): - # Arrange - activity = Activity( - type=ActivityTypes.invoke, - name="composeExtension/fetchTask", - value={ - "data": {"key": "value"}, - "context": {"theme": "dark"}, - "commandId": "test_command", - "commandContext": "command_context_test", - "botMessagePreviewAction": "message_action", - "botActivityPreview": [{"id": "123"}], - "messagePayload": {"id": "abc123"}, - }, - ) - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_messaging_extension_fetch_task" - - async def test_on_teams_messaging_extension_configuration_query_settings_url(self): - # Arrange - activity = Activity( - type=ActivityTypes.invoke, - name="composeExtension/querySettingUrl", - value={ - "commandId": "test_command", - "parameters": [], - "messagingExtensionQueryOptions": {"skip": 1, "count": 1}, - "state": "state_string", - }, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_invoke_activity" - assert ( - bot.record[1] - == "on_teams_messaging_extension_configuration_query_settings_url" - ) - - async def test_on_teams_messaging_extension_configuration_setting(self): - # Arrange - activity = Activity( - type=ActivityTypes.invoke, - name="composeExtension/setting", - value={"key": "value"}, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_messaging_extension_configuration_setting" - - async def test_on_teams_messaging_extension_card_button_clicked(self): - # Arrange - activity = Activity( - type=ActivityTypes.invoke, - name="composeExtension/onCardButtonClicked", - value={"key": "value"}, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_messaging_extension_card_button_clicked" - - async def test_on_teams_task_module_fetch(self): - # Arrange - activity = Activity( - type=ActivityTypes.invoke, - name="task/fetch", - value={ - "data": {"key": "value"}, - "context": TaskModuleRequestContext().serialize(), - }, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_task_module_fetch" - - async def test_on_teams_task_module_submit(self): - # Arrange - activity = Activity( - type=ActivityTypes.invoke, - name="task/submit", - value={ - "data": {"key": "value"}, - "context": TaskModuleRequestContext().serialize(), - }, - ) - - turn_context = TurnContext(SimpleAdapter(), activity) - - # Act - bot = TestingTeamsActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 2 - assert bot.record[0] == "on_invoke_activity" - assert bot.record[1] == "on_teams_task_module_submit" +from typing import List + +import aiounittest +from botbuilder.core import BotAdapter, TurnContext +from botbuilder.core.teams import TeamsActivityHandler +from botbuilder.schema import ( + Activity, + ActivityTypes, + ChannelAccount, + ConversationReference, + ResourceResponse, +) +from botbuilder.schema.teams import ( + AppBasedLinkQuery, + ChannelInfo, + FileConsentCardResponse, + MessageActionsPayload, + MessagingExtensionAction, + MessagingExtensionQuery, + O365ConnectorCardActionQuery, + TaskModuleRequest, + TaskModuleRequestContext, + TeamInfo, + TeamsChannelAccount, +) +from botframework.connector import Channels +from simple_adapter import SimpleAdapter + + +class TestingTeamsActivityHandler(TeamsActivityHandler): + __test__ = False + + def __init__(self): + self.record: List[str] = [] + + async def on_conversation_update_activity(self, turn_context: TurnContext): + self.record.append("on_conversation_update_activity") + return await super().on_conversation_update_activity(turn_context) + + async def on_teams_members_removed( + self, teams_members_removed: [TeamsChannelAccount], turn_context: TurnContext + ): + self.record.append("on_teams_members_removed") + return await super().on_teams_members_removed( + teams_members_removed, turn_context + ) + + async def on_message_activity(self, turn_context: TurnContext): + self.record.append("on_message_activity") + return await super().on_message_activity(turn_context) + + async def on_token_response_event(self, turn_context: TurnContext): + self.record.append("on_token_response_event") + return await super().on_token_response_event(turn_context) + + async def on_event(self, turn_context: TurnContext): + self.record.append("on_event") + return await super().on_event(turn_context) + + async def on_unrecognized_activity_type(self, turn_context: TurnContext): + self.record.append("on_unrecognized_activity_type") + return await super().on_unrecognized_activity_type(turn_context) + + async def on_teams_channel_created( + self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext + ): + self.record.append("on_teams_channel_created") + return await super().on_teams_channel_created( + channel_info, team_info, turn_context + ) + + async def on_teams_channel_renamed( + self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext + ): + self.record.append("on_teams_channel_renamed") + return await super().on_teams_channel_renamed( + channel_info, team_info, turn_context + ) + + async def on_teams_channel_deleted( + self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext + ): + self.record.append("on_teams_channel_deleted") + return await super().on_teams_channel_renamed( + channel_info, team_info, turn_context + ) + + async def on_teams_team_renamed_activity( + self, team_info: TeamInfo, turn_context: TurnContext + ): + self.record.append("on_teams_team_renamed_activity") + return await super().on_teams_team_renamed_activity(team_info, turn_context) + + async def on_invoke_activity(self, turn_context: TurnContext): + self.record.append("on_invoke_activity") + return await super().on_invoke_activity(turn_context) + + async def on_teams_signin_verify_state(self, turn_context: TurnContext): + self.record.append("on_teams_signin_verify_state") + return await super().on_teams_signin_verify_state(turn_context) + + async def on_teams_file_consent( + self, + turn_context: TurnContext, + file_consent_card_response: FileConsentCardResponse, + ): + self.record.append("on_teams_file_consent") + return await super().on_teams_file_consent( + turn_context, file_consent_card_response + ) + + async def on_teams_file_consent_accept( + self, + turn_context: TurnContext, + file_consent_card_response: FileConsentCardResponse, + ): + self.record.append("on_teams_file_consent_accept") + return await super().on_teams_file_consent_accept( + turn_context, file_consent_card_response + ) + + async def on_teams_file_consent_decline( + self, + turn_context: TurnContext, + file_consent_card_response: FileConsentCardResponse, + ): + self.record.append("on_teams_file_consent_decline") + return await super().on_teams_file_consent_decline( + turn_context, file_consent_card_response + ) + + async def on_teams_o365_connector_card_action( + self, turn_context: TurnContext, query: O365ConnectorCardActionQuery + ): + self.record.append("on_teams_o365_connector_card_action") + return await super().on_teams_o365_connector_card_action(turn_context, query) + + async def on_teams_app_based_link_query( + self, turn_context: TurnContext, query: AppBasedLinkQuery + ): + self.record.append("on_teams_app_based_link_query") + return await super().on_teams_app_based_link_query(turn_context, query) + + async def on_teams_messaging_extension_query( + self, turn_context: TurnContext, query: MessagingExtensionQuery + ): + self.record.append("on_teams_messaging_extension_query") + return await super().on_teams_messaging_extension_query(turn_context, query) + + async def on_teams_messaging_extension_submit_action_dispatch( + self, turn_context: TurnContext, action: MessagingExtensionAction + ): + self.record.append("on_teams_messaging_extension_submit_action_dispatch") + return await super().on_teams_messaging_extension_submit_action_dispatch( + turn_context, action + ) + + async def on_teams_messaging_extension_submit_action( + self, turn_context: TurnContext, action: MessagingExtensionAction + ): + self.record.append("on_teams_messaging_extension_submit_action") + return await super().on_teams_messaging_extension_submit_action( + turn_context, action + ) + + async def on_teams_messaging_extension_bot_message_preview_edit( + self, turn_context: TurnContext, action: MessagingExtensionAction + ): + self.record.append("on_teams_messaging_extension_bot_message_preview_edit") + return await super().on_teams_messaging_extension_bot_message_preview_edit( + turn_context, action + ) + + async def on_teams_messaging_extension_bot_message_preview_send( + self, turn_context: TurnContext, action: MessagingExtensionAction + ): + self.record.append("on_teams_messaging_extension_bot_message_preview_send") + return await super().on_teams_messaging_extension_bot_message_preview_send( + turn_context, action + ) + + async def on_teams_messaging_extension_fetch_task( + self, turn_context: TurnContext, action: MessagingExtensionAction + ): + self.record.append("on_teams_messaging_extension_fetch_task") + return await super().on_teams_messaging_extension_fetch_task( + turn_context, action + ) + + async def on_teams_messaging_extension_configuration_query_settings_url( + self, turn_context: TurnContext, query: MessagingExtensionQuery + ): + self.record.append( + "on_teams_messaging_extension_configuration_query_settings_url" + ) + return await super().on_teams_messaging_extension_configuration_query_settings_url( + turn_context, query + ) + + async def on_teams_messaging_extension_configuration_setting( + self, turn_context: TurnContext, settings + ): + self.record.append("on_teams_messaging_extension_configuration_setting") + return await super().on_teams_messaging_extension_configuration_setting( + turn_context, settings + ) + + async def on_teams_messaging_extension_card_button_clicked( + self, turn_context: TurnContext, card_data + ): + self.record.append("on_teams_messaging_extension_card_button_clicked") + return await super().on_teams_messaging_extension_card_button_clicked( + turn_context, card_data + ) + + async def on_teams_task_module_fetch( + self, turn_context: TurnContext, task_module_request + ): + self.record.append("on_teams_task_module_fetch") + return await super().on_teams_task_module_fetch( + turn_context, task_module_request + ) + + async def on_teams_task_module_submit( # pylint: disable=unused-argument + self, turn_context: TurnContext, task_module_request: TaskModuleRequest + ): + self.record.append("on_teams_task_module_submit") + return await super().on_teams_task_module_submit( + turn_context, task_module_request + ) + + +class NotImplementedAdapter(BotAdapter): + async def delete_activity( + self, context: TurnContext, reference: ConversationReference + ): + raise NotImplementedError() + + async def send_activities( + self, context: TurnContext, activities: List[Activity] + ) -> List[ResourceResponse]: + raise NotImplementedError() + + async def update_activity(self, context: TurnContext, activity: Activity): + raise NotImplementedError() + + +class TestTeamsActivityHandler(aiounittest.AsyncTestCase): + async def test_on_teams_channel_created_activity(self): + # arrange + activity = Activity( + type=ActivityTypes.conversation_update, + channel_data={ + "eventType": "channelCreated", + "channel": {"id": "asdfqwerty", "name": "new_channel"}, + }, + channel_id=Channels.ms_teams, + ) + + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_channel_created" + + async def test_on_teams_channel_renamed_activity(self): + # arrange + activity = Activity( + type=ActivityTypes.conversation_update, + channel_data={ + "eventType": "channelRenamed", + "channel": {"id": "asdfqwerty", "name": "new_channel"}, + }, + channel_id=Channels.ms_teams, + ) + + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_channel_renamed" + + async def test_on_teams_channel_deleted_activity(self): + # arrange + activity = Activity( + type=ActivityTypes.conversation_update, + channel_data={ + "eventType": "channelDeleted", + "channel": {"id": "asdfqwerty", "name": "new_channel"}, + }, + channel_id=Channels.ms_teams, + ) + + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_channel_deleted" + + async def test_on_teams_team_renamed_activity(self): + # arrange + activity = Activity( + type=ActivityTypes.conversation_update, + channel_data={ + "eventType": "teamRenamed", + "team": {"id": "team_id_1", "name": "new_team_name"}, + }, + channel_id=Channels.ms_teams, + ) + + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_team_renamed_activity" + + async def test_on_teams_members_removed_activity(self): + # arrange + activity = Activity( + type=ActivityTypes.conversation_update, + channel_data={"eventType": "teamMemberRemoved"}, + members_removed=[ + ChannelAccount( + id="123", + name="test_user", + aad_object_id="asdfqwerty", + role="tester", + ) + ], + channel_id=Channels.ms_teams, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_members_removed" + + async def test_on_signin_verify_state(self): + # arrange + activity = Activity(type=ActivityTypes.invoke, name="signin/verifyState") + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_signin_verify_state" + + async def test_on_file_consent_accept_activity(self): + # arrange + activity = Activity( + type=ActivityTypes.invoke, + name="fileConsent/invoke", + value={"action": "accept"}, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 3 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_file_consent" + assert bot.record[2] == "on_teams_file_consent_accept" + + async def test_on_file_consent_decline_activity(self): + # Arrange + activity = Activity( + type=ActivityTypes.invoke, + name="fileConsent/invoke", + value={"action": "decline"}, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 3 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_file_consent" + assert bot.record[2] == "on_teams_file_consent_decline" + + async def test_on_file_consent_bad_action_activity(self): + # Arrange + activity = Activity( + type=ActivityTypes.invoke, + name="fileConsent/invoke", + value={"action": "bad_action"}, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_file_consent" + + async def test_on_teams_o365_connector_card_action(self): + # arrange + activity = Activity( + type=ActivityTypes.invoke, + name="actionableMessage/executeAction", + value={"body": "body_here", "actionId": "action_id_here"}, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_o365_connector_card_action" + + async def test_on_app_based_link_query(self): + # arrange + activity = Activity( + type=ActivityTypes.invoke, + name="composeExtension/query", + value={"url": "http://www.test.com"}, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_messaging_extension_query" + + async def test_on_teams_messaging_extension_bot_message_preview_edit_activity(self): + # Arrange + + activity = Activity( + type=ActivityTypes.invoke, + name="composeExtension/submitAction", + value={ + "data": {"key": "value"}, + "context": {"theme": "dark"}, + "commandId": "test_command", + "commandContext": "command_context_test", + "botMessagePreviewAction": "edit", + "botActivityPreview": [{"id": "activity123"}], + "messagePayload": {"id": "payloadid"}, + }, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 3 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_messaging_extension_submit_action_dispatch" + assert bot.record[2] == "on_teams_messaging_extension_bot_message_preview_edit" + + async def test_on_teams_messaging_extension_bot_message_send_activity(self): + # Arrange + activity = Activity( + type=ActivityTypes.invoke, + name="composeExtension/submitAction", + value={ + "data": {"key": "value"}, + "context": {"theme": "dark"}, + "commandId": "test_command", + "commandContext": "command_context_test", + "botMessagePreviewAction": "send", + "botActivityPreview": [{"id": "123"}], + "messagePayload": {"id": "abc"}, + }, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 3 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_messaging_extension_submit_action_dispatch" + assert bot.record[2] == "on_teams_messaging_extension_bot_message_preview_send" + + async def test_on_teams_messaging_extension_bot_message_send_activity_with_none( + self, + ): + # Arrange + activity = Activity( + type=ActivityTypes.invoke, + name="composeExtension/submitAction", + value={ + "data": {"key": "value"}, + "context": {"theme": "dark"}, + "commandId": "test_command", + "commandContext": "command_context_test", + "botMessagePreviewAction": None, + "botActivityPreview": [{"id": "test123"}], + "messagePayload": {"id": "payloadid123"}, + }, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 3 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_messaging_extension_submit_action_dispatch" + assert bot.record[2] == "on_teams_messaging_extension_submit_action" + + async def test_on_teams_messaging_extension_bot_message_send_activity_with_empty_string( + self, + ): + # Arrange + activity = Activity( + type=ActivityTypes.invoke, + name="composeExtension/submitAction", + value={ + "data": {"key": "value"}, + "context": {"theme": "dark"}, + "commandId": "test_command", + "commandContext": "command_context_test", + "botMessagePreviewAction": "", + "botActivityPreview": [Activity().serialize()], + "messagePayload": MessageActionsPayload().serialize(), + }, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 3 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_messaging_extension_submit_action_dispatch" + assert bot.record[2] == "on_teams_messaging_extension_submit_action" + + async def test_on_teams_messaging_extension_fetch_task(self): + # Arrange + activity = Activity( + type=ActivityTypes.invoke, + name="composeExtension/fetchTask", + value={ + "data": {"key": "value"}, + "context": {"theme": "dark"}, + "commandId": "test_command", + "commandContext": "command_context_test", + "botMessagePreviewAction": "message_action", + "botActivityPreview": [{"id": "123"}], + "messagePayload": {"id": "abc123"}, + }, + ) + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_messaging_extension_fetch_task" + + async def test_on_teams_messaging_extension_configuration_query_settings_url(self): + # Arrange + activity = Activity( + type=ActivityTypes.invoke, + name="composeExtension/querySettingUrl", + value={ + "commandId": "test_command", + "parameters": [], + "messagingExtensionQueryOptions": {"skip": 1, "count": 1}, + "state": "state_string", + }, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_invoke_activity" + assert ( + bot.record[1] + == "on_teams_messaging_extension_configuration_query_settings_url" + ) + + async def test_on_teams_messaging_extension_configuration_setting(self): + # Arrange + activity = Activity( + type=ActivityTypes.invoke, + name="composeExtension/setting", + value={"key": "value"}, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_messaging_extension_configuration_setting" + + async def test_on_teams_messaging_extension_card_button_clicked(self): + # Arrange + activity = Activity( + type=ActivityTypes.invoke, + name="composeExtension/onCardButtonClicked", + value={"key": "value"}, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_messaging_extension_card_button_clicked" + + async def test_on_teams_task_module_fetch(self): + # Arrange + activity = Activity( + type=ActivityTypes.invoke, + name="task/fetch", + value={ + "data": {"key": "value"}, + "context": TaskModuleRequestContext().serialize(), + }, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_task_module_fetch" + + async def test_on_teams_task_module_submit(self): + # Arrange + activity = Activity( + type=ActivityTypes.invoke, + name="task/submit", + value={ + "data": {"key": "value"}, + "context": TaskModuleRequestContext().serialize(), + }, + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_invoke_activity" + assert bot.record[1] == "on_teams_task_module_submit" diff --git a/libraries/botbuilder-core/tests/test_activity_handler.py b/libraries/botbuilder-core/tests/test_activity_handler.py --- a/libraries/botbuilder-core/tests/test_activity_handler.py +++ b/libraries/botbuilder-core/tests/test_activity_handler.py @@ -1,101 +1,103 @@ -from typing import List - -import aiounittest -from botbuilder.core import ActivityHandler, BotAdapter, TurnContext -from botbuilder.schema import ( - Activity, - ActivityTypes, - ChannelAccount, - ConversationReference, - MessageReaction, - ResourceResponse, -) - - -class TestingActivityHandler(ActivityHandler): - def __init__(self): - self.record: List[str] = [] - - async def on_message_activity(self, turn_context: TurnContext): - self.record.append("on_message_activity") - return await super().on_message_activity(turn_context) - - async def on_members_added_activity( - self, members_added: ChannelAccount, turn_context: TurnContext - ): - self.record.append("on_members_added_activity") - return await super().on_members_added_activity(members_added, turn_context) - - async def on_members_removed_activity( - self, members_removed: ChannelAccount, turn_context: TurnContext - ): - self.record.append("on_members_removed_activity") - return await super().on_members_removed_activity(members_removed, turn_context) - - async def on_message_reaction_activity(self, turn_context: TurnContext): - self.record.append("on_message_reaction_activity") - return await super().on_message_reaction_activity(turn_context) - - async def on_reactions_added( - self, message_reactions: List[MessageReaction], turn_context: TurnContext - ): - self.record.append("on_reactions_added") - return await super().on_reactions_added(message_reactions, turn_context) - - async def on_reactions_removed( - self, message_reactions: List[MessageReaction], turn_context: TurnContext - ): - self.record.append("on_reactions_removed") - return await super().on_reactions_removed(message_reactions, turn_context) - - async def on_token_response_event(self, turn_context: TurnContext): - self.record.append("on_token_response_event") - return await super().on_token_response_event(turn_context) - - async def on_event(self, turn_context: TurnContext): - self.record.append("on_event") - return await super().on_event(turn_context) - - async def on_unrecognized_activity_type(self, turn_context: TurnContext): - self.record.append("on_unrecognized_activity_type") - return await super().on_unrecognized_activity_type(turn_context) - - -class NotImplementedAdapter(BotAdapter): - async def delete_activity( - self, context: TurnContext, reference: ConversationReference - ): - raise NotImplementedError() - - async def send_activities( - self, context: TurnContext, activities: List[Activity] - ) -> List[ResourceResponse]: - raise NotImplementedError() - - async def update_activity(self, context: TurnContext, activity: Activity): - raise NotImplementedError() - - -class TestActivityHandler(aiounittest.AsyncTestCase): - async def test_message_reaction(self): - # Note the code supports multiple adds and removes in the same activity though - # a channel may decide to send separate activities for each. For example, Teams - # sends separate activities each with a single add and a single remove. - - # Arrange - activity = Activity( - type=ActivityTypes.message_reaction, - reactions_added=[MessageReaction(type="sad")], - reactions_removed=[MessageReaction(type="angry")], - ) - turn_context = TurnContext(NotImplementedAdapter(), activity) - - # Act - bot = TestingActivityHandler() - await bot.on_turn(turn_context) - - # Assert - assert len(bot.record) == 3 - assert bot.record[0] == "on_message_reaction_activity" - assert bot.record[1] == "on_reactions_added" - assert bot.record[2] == "on_reactions_removed" +from typing import List + +import aiounittest +from botbuilder.core import ActivityHandler, BotAdapter, TurnContext +from botbuilder.schema import ( + Activity, + ActivityTypes, + ChannelAccount, + ConversationReference, + MessageReaction, + ResourceResponse, +) + + +class TestingActivityHandler(ActivityHandler): + __test__ = False + + def __init__(self): + self.record: List[str] = [] + + async def on_message_activity(self, turn_context: TurnContext): + self.record.append("on_message_activity") + return await super().on_message_activity(turn_context) + + async def on_members_added_activity( + self, members_added: ChannelAccount, turn_context: TurnContext + ): + self.record.append("on_members_added_activity") + return await super().on_members_added_activity(members_added, turn_context) + + async def on_members_removed_activity( + self, members_removed: ChannelAccount, turn_context: TurnContext + ): + self.record.append("on_members_removed_activity") + return await super().on_members_removed_activity(members_removed, turn_context) + + async def on_message_reaction_activity(self, turn_context: TurnContext): + self.record.append("on_message_reaction_activity") + return await super().on_message_reaction_activity(turn_context) + + async def on_reactions_added( + self, message_reactions: List[MessageReaction], turn_context: TurnContext + ): + self.record.append("on_reactions_added") + return await super().on_reactions_added(message_reactions, turn_context) + + async def on_reactions_removed( + self, message_reactions: List[MessageReaction], turn_context: TurnContext + ): + self.record.append("on_reactions_removed") + return await super().on_reactions_removed(message_reactions, turn_context) + + async def on_token_response_event(self, turn_context: TurnContext): + self.record.append("on_token_response_event") + return await super().on_token_response_event(turn_context) + + async def on_event(self, turn_context: TurnContext): + self.record.append("on_event") + return await super().on_event(turn_context) + + async def on_unrecognized_activity_type(self, turn_context: TurnContext): + self.record.append("on_unrecognized_activity_type") + return await super().on_unrecognized_activity_type(turn_context) + + +class NotImplementedAdapter(BotAdapter): + async def delete_activity( + self, context: TurnContext, reference: ConversationReference + ): + raise NotImplementedError() + + async def send_activities( + self, context: TurnContext, activities: List[Activity] + ) -> List[ResourceResponse]: + raise NotImplementedError() + + async def update_activity(self, context: TurnContext, activity: Activity): + raise NotImplementedError() + + +class TestActivityHandler(aiounittest.AsyncTestCase): + async def test_message_reaction(self): + # Note the code supports multiple adds and removes in the same activity though + # a channel may decide to send separate activities for each. For example, Teams + # sends separate activities each with a single add and a single remove. + + # Arrange + activity = Activity( + type=ActivityTypes.message_reaction, + reactions_added=[MessageReaction(type="sad")], + reactions_removed=[MessageReaction(type="angry")], + ) + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 3 + assert bot.record[0] == "on_message_reaction_activity" + assert bot.record[1] == "on_reactions_added" + assert bot.record[2] == "on_reactions_removed" diff --git a/libraries/botbuilder-core/tests/test_bot_adapter.py b/libraries/botbuilder-core/tests/test_bot_adapter.py --- a/libraries/botbuilder-core/tests/test_bot_adapter.py +++ b/libraries/botbuilder-core/tests/test_bot_adapter.py @@ -1,86 +1,86 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -import uuid -from typing import List -import aiounittest - -from botbuilder.core import TurnContext -from botbuilder.core.adapters import TestAdapter -from botbuilder.schema import ( - Activity, - ConversationAccount, - ConversationReference, - ChannelAccount, -) - -from simple_adapter import SimpleAdapter -from call_counting_middleware import CallCountingMiddleware -from test_message import TestMessage - - -class TestBotAdapter(aiounittest.AsyncTestCase): - def test_adapter_single_use(self): - adapter = SimpleAdapter() - adapter.use(CallCountingMiddleware()) - - def test_adapter_use_chaining(self): - adapter = SimpleAdapter() - adapter.use(CallCountingMiddleware()).use(CallCountingMiddleware()) - - async def test_pass_resource_responses_through(self): - def validate_responses( # pylint: disable=unused-argument - activities: List[Activity], - ): - pass # no need to do anything. - - adapter = SimpleAdapter(call_on_send=validate_responses) - context = TurnContext(adapter, Activity()) - - activity_id = str(uuid.uuid1()) - activity = TestMessage.message(activity_id) - - resource_response = await context.send_activity(activity) - self.assertTrue( - resource_response.id != activity_id, "Incorrect response Id returned" - ) - - async def test_continue_conversation_direct_msg(self): - callback_invoked = False - adapter = TestAdapter() - reference = ConversationReference( - activity_id="activityId", - bot=ChannelAccount(id="channelId", name="testChannelAccount", role="bot"), - channel_id="testChannel", - service_url="testUrl", - conversation=ConversationAccount( - conversation_type="", - id="testConversationId", - is_group=False, - name="testConversationName", - role="user", - ), - user=ChannelAccount(id="channelId", name="testChannelAccount", role="bot"), - ) - - async def continue_callback(turn_context): # pylint: disable=unused-argument - nonlocal callback_invoked - callback_invoked = True - - await adapter.continue_conversation(reference, continue_callback, "MyBot") - self.assertTrue(callback_invoked) - - async def test_turn_error(self): - async def on_error(turn_context: TurnContext, err: Exception): - nonlocal self - self.assertIsNotNone(turn_context, "turn_context not found.") - self.assertIsNotNone(err, "error not found.") - self.assertEqual(err.__class__, Exception, "unexpected error thrown.") - - adapter = SimpleAdapter() - adapter.on_turn_error = on_error - - def handler(context: TurnContext): # pylint: disable=unused-argument - raise Exception - - await adapter.process_request(TestMessage.message(), handler) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import uuid +from typing import List +import aiounittest + +from botbuilder.core import TurnContext +from botbuilder.core.adapters import TestAdapter +from botbuilder.schema import ( + Activity, + ConversationAccount, + ConversationReference, + ChannelAccount, +) + +from simple_adapter import SimpleAdapter +from call_counting_middleware import CallCountingMiddleware +from test_message import TestMessage + + +class TestBotAdapter(aiounittest.AsyncTestCase): + def test_adapter_single_use(self): + adapter = SimpleAdapter() + adapter.use(CallCountingMiddleware()) + + def test_adapter_use_chaining(self): + adapter = SimpleAdapter() + adapter.use(CallCountingMiddleware()).use(CallCountingMiddleware()) + + async def test_pass_resource_responses_through(self): + def validate_responses( # pylint: disable=unused-argument + activities: List[Activity], + ): + pass # no need to do anything. + + adapter = SimpleAdapter(call_on_send=validate_responses) + context = TurnContext(adapter, Activity()) + + activity_id = str(uuid.uuid1()) + activity = TestMessage.message(activity_id) + + resource_response = await context.send_activity(activity) + self.assertTrue( + resource_response.id != activity_id, "Incorrect response Id returned" + ) + + async def test_continue_conversation_direct_msg(self): + callback_invoked = False + adapter = TestAdapter() + reference = ConversationReference( + activity_id="activityId", + bot=ChannelAccount(id="channelId", name="testChannelAccount", role="bot"), + channel_id="testChannel", + service_url="testUrl", + conversation=ConversationAccount( + conversation_type="", + id="testConversationId", + is_group=False, + name="testConversationName", + role="user", + ), + user=ChannelAccount(id="channelId", name="testChannelAccount", role="bot"), + ) + + async def continue_callback(turn_context): # pylint: disable=unused-argument + nonlocal callback_invoked + callback_invoked = True + + await adapter.continue_conversation(reference, continue_callback, "MyBot") + self.assertTrue(callback_invoked) + + async def test_turn_error(self): + async def on_error(turn_context: TurnContext, err: Exception): + nonlocal self + self.assertIsNotNone(turn_context, "turn_context not found.") + self.assertIsNotNone(err, "error not found.") + self.assertEqual(err.__class__, Exception, "unexpected error thrown.") + + adapter = SimpleAdapter() + adapter.on_turn_error = on_error + + def handler(context: TurnContext): # pylint: disable=unused-argument + raise Exception + + await adapter.process_request(TestMessage.message(), handler) diff --git a/libraries/botbuilder-core/tests/test_bot_state.py b/libraries/botbuilder-core/tests/test_bot_state.py --- a/libraries/botbuilder-core/tests/test_bot_state.py +++ b/libraries/botbuilder-core/tests/test_bot_state.py @@ -1,483 +1,485 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -from unittest.mock import MagicMock -import aiounittest - -from botbuilder.core import ( - BotState, - ConversationState, - MemoryStorage, - Storage, - StoreItem, - TurnContext, - UserState, -) -from botbuilder.core.adapters import TestAdapter -from botbuilder.schema import Activity, ConversationAccount - -from test_utilities import TestUtilities - -RECEIVED_MESSAGE = Activity(type="message", text="received") -STORAGE_KEY = "stateKey" - - -def cached_state(context, state_key): - cached = context.services.get(state_key) - return cached["state"] if cached is not None else None - - -def key_factory(context): - assert context is not None - return STORAGE_KEY - - -class BotStateForTest(BotState): - def __init__(self, storage: Storage): - super().__init__(storage, f"BotState:BotState") - - def get_storage_key(self, turn_context: TurnContext) -> str: - return f"botstate/{turn_context.activity.channel_id}/{turn_context.activity.conversation.id}/BotState" - - -class CustomState(StoreItem): - def __init__(self, custom_string: str = None, e_tag: str = "*"): - super().__init__(custom_string=custom_string, e_tag=e_tag) - - -class TestPocoState: - def __init__(self, value=None): - self.value = value - - -class TestBotState(aiounittest.AsyncTestCase): - storage = MemoryStorage() - adapter = TestAdapter() - context = TurnContext(adapter, RECEIVED_MESSAGE) - middleware = BotState(storage, key_factory) - - def test_state_empty_name(self): - # Arrange - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - - # Act - with self.assertRaises(TypeError) as _: - user_state.create_property("") - - def test_state_none_name(self): - # Arrange - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - - # Act - with self.assertRaises(TypeError) as _: - user_state.create_property(None) - - async def test_storage_not_called_no_changes(self): - """Verify storage not called when no changes are made""" - # Mock a storage provider, which counts read/writes - dictionary = {} - - async def mock_write_result(self): # pylint: disable=unused-argument - return - - async def mock_read_result(self): # pylint: disable=unused-argument - return {} - - mock_storage = MemoryStorage(dictionary) - mock_storage.write = MagicMock(side_effect=mock_write_result) - mock_storage.read = MagicMock(side_effect=mock_read_result) - - # Arrange - user_state = UserState(mock_storage) - context = TestUtilities.create_empty_context() - - # Act - property_a = user_state.create_property("property_a") - self.assertEqual(mock_storage.write.call_count, 0) - await user_state.save_changes(context) - await property_a.set(context, "hello") - self.assertEqual(mock_storage.read.call_count, 1) # Initial save bumps count - self.assertEqual(mock_storage.write.call_count, 0) # Initial save bumps count - await property_a.set(context, "there") - self.assertEqual( - mock_storage.write.call_count, 0 - ) # Set on property should not bump - await user_state.save_changes(context) - self.assertEqual(mock_storage.write.call_count, 1) # Explicit save should bump - value_a = await property_a.get(context) - self.assertEqual("there", value_a) - self.assertEqual(mock_storage.write.call_count, 1) # Gets should not bump - await user_state.save_changes(context) - self.assertEqual(mock_storage.write.call_count, 1) - await property_a.delete(context) # Delete alone no bump - self.assertEqual(mock_storage.write.call_count, 1) - await user_state.save_changes(context) # Save when dirty should bump - self.assertEqual(mock_storage.write.call_count, 2) - self.assertEqual(mock_storage.read.call_count, 1) - await user_state.save_changes(context) # Save not dirty should not bump - self.assertEqual(mock_storage.write.call_count, 2) - self.assertEqual(mock_storage.read.call_count, 1) - - async def test_state_set_no_load(self): - """Should be able to set a property with no Load""" - # Arrange - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - context = TestUtilities.create_empty_context() - - # Act - property_a = user_state.create_property("property_a") - await property_a.set(context, "hello") - - async def test_state_multiple_loads(self): - """Should be able to load multiple times""" - # Arrange - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - context = TestUtilities.create_empty_context() - - # Act - user_state.create_property("property_a") - await user_state.load(context) - await user_state.load(context) - - async def test_state_get_no_load_with_default(self): - """Should be able to get a property with no Load and default""" - # Arrange - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - context = TestUtilities.create_empty_context() - - # Act - property_a = user_state.create_property("property_a") - value_a = await property_a.get(context, lambda: "Default!") - self.assertEqual("Default!", value_a) - - async def test_state_get_no_load_no_default(self): - """Cannot get a string with no default set""" - # Arrange - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - context = TestUtilities.create_empty_context() - - # Act - property_a = user_state.create_property("property_a") - value_a = await property_a.get(context) - - # Assert - self.assertIsNone(value_a) - - async def test_state_poco_no_default(self): - """Cannot get a POCO with no default set""" - # Arrange - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - context = TestUtilities.create_empty_context() - - # Act - test_property = user_state.create_property("test") - value = await test_property.get(context) - - # Assert - self.assertIsNone(value) - - async def test_state_bool_no_default(self): - """Cannot get a bool with no default set""" - # Arange - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - context = TestUtilities.create_empty_context() - - # Act - test_property = user_state.create_property("test") - value = await test_property.get(context) - - # Assert - self.assertFalse(value) - - async def test_state_set_after_save(self): - """Verify setting property after save""" - # Arrange - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - context = TestUtilities.create_empty_context() - - # Act - property_a = user_state.create_property("property-a") - property_b = user_state.create_property("property-b") - - await user_state.load(context) - await property_a.set(context, "hello") - await property_b.set(context, "world") - await user_state.save_changes(context) - - await property_a.set(context, "hello2") - - async def test_state_multiple_save(self): - """Verify multiple saves""" - # Arrange - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - context = TestUtilities.create_empty_context() - - # Act - property_a = user_state.create_property("property-a") - property_b = user_state.create_property("property-b") - - await user_state.load(context) - await property_a.set(context, "hello") - await property_b.set(context, "world") - await user_state.save_changes(context) - - await property_a.set(context, "hello2") - await user_state.save_changes(context) - value_a = await property_a.get(context) - self.assertEqual("hello2", value_a) - - async def test_load_set_save(self): - # Arrange - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - context = TestUtilities.create_empty_context() - - # Act - property_a = user_state.create_property("property-a") - property_b = user_state.create_property("property-b") - - await user_state.load(context) - await property_a.set(context, "hello") - await property_b.set(context, "world") - await user_state.save_changes(context) - - # Assert - obj = dictionary["EmptyContext/users/[email protected]"] - self.assertEqual("hello", obj["property-a"]) - self.assertEqual("world", obj["property-b"]) - - async def test_load_set_save_twice(self): - # Arrange - dictionary = {} - context = TestUtilities.create_empty_context() - - # Act - user_state = UserState(MemoryStorage(dictionary)) - - property_a = user_state.create_property("property-a") - property_b = user_state.create_property("property-b") - property_c = user_state.create_property("property-c") - - await user_state.load(context) - await property_a.set(context, "hello") - await property_b.set(context, "world") - await property_c.set(context, "test") - await user_state.save_changes(context) - - # Assert - obj = dictionary["EmptyContext/users/[email protected]"] - self.assertEqual("hello", obj["property-a"]) - self.assertEqual("world", obj["property-b"]) - - # Act 2 - user_state2 = UserState(MemoryStorage(dictionary)) - - property_a2 = user_state2.create_property("property-a") - property_b2 = user_state2.create_property("property-b") - - await user_state2.load(context) - await property_a2.set(context, "hello-2") - await property_b2.set(context, "world-2") - await user_state2.save_changes(context) - - # Assert 2 - obj2 = dictionary["EmptyContext/users/[email protected]"] - self.assertEqual("hello-2", obj2["property-a"]) - self.assertEqual("world-2", obj2["property-b"]) - self.assertEqual("test", obj2["property-c"]) - - async def test_load_save_delete(self): - # Arrange - dictionary = {} - context = TestUtilities.create_empty_context() - - # Act - user_state = UserState(MemoryStorage(dictionary)) - - property_a = user_state.create_property("property-a") - property_b = user_state.create_property("property-b") - - await user_state.load(context) - await property_a.set(context, "hello") - await property_b.set(context, "world") - await user_state.save_changes(context) - - # Assert - obj = dictionary["EmptyContext/users/[email protected]"] - self.assertEqual("hello", obj["property-a"]) - self.assertEqual("world", obj["property-b"]) - - # Act 2 - user_state2 = UserState(MemoryStorage(dictionary)) - - property_a2 = user_state2.create_property("property-a") - property_b2 = user_state2.create_property("property-b") - - await user_state2.load(context) - await property_a2.set(context, "hello-2") - await property_b2.delete(context) - await user_state2.save_changes(context) - - # Assert 2 - obj2 = dictionary["EmptyContext/users/[email protected]"] - self.assertEqual("hello-2", obj2["property-a"]) - with self.assertRaises(KeyError) as _: - obj2["property-b"] # pylint: disable=pointless-statement - - async def test_state_use_bot_state_directly(self): - async def exec_test(context: TurnContext): - # pylint: disable=unnecessary-lambda - bot_state_manager = BotStateForTest(MemoryStorage()) - test_property = bot_state_manager.create_property("test") - - # read initial state object - await bot_state_manager.load(context) - - custom_state = await test_property.get(context, lambda: CustomState()) - - # this should be a 'CustomState' as nothing is currently stored in storage - assert isinstance(custom_state, CustomState) - - # amend property and write to storage - custom_state.custom_string = "test" - await bot_state_manager.save_changes(context) - - custom_state.custom_string = "asdfsadf" - - # read into context again - await bot_state_manager.load(context, True) - - custom_state = await test_property.get(context) - - # check object read from value has the correct value for custom_string - assert custom_state.custom_string == "test" - - adapter = TestAdapter(exec_test) - await adapter.send("start") - - async def test_user_state_bad_from_throws(self): - dictionary = {} - user_state = UserState(MemoryStorage(dictionary)) - context = TestUtilities.create_empty_context() - context.activity.from_property = None - test_property = user_state.create_property("test") - with self.assertRaises(AttributeError): - await test_property.get(context) - - async def test_conversation_state_bad_conversation_throws(self): - dictionary = {} - user_state = ConversationState(MemoryStorage(dictionary)) - context = TestUtilities.create_empty_context() - context.activity.conversation = None - test_property = user_state.create_property("test") - with self.assertRaises(AttributeError): - await test_property.get(context) - - async def test_clear_and_save(self): - # pylint: disable=unnecessary-lambda - turn_context = TestUtilities.create_empty_context() - turn_context.activity.conversation = ConversationAccount(id="1234") - - storage = MemoryStorage({}) - - # Turn 0 - bot_state1 = ConversationState(storage) - ( - await bot_state1.create_property("test-name").get( - turn_context, lambda: TestPocoState() - ) - ).value = "test-value" - await bot_state1.save_changes(turn_context) - - # Turn 1 - bot_state2 = ConversationState(storage) - value1 = ( - await bot_state2.create_property("test-name").get( - turn_context, lambda: TestPocoState(value="default-value") - ) - ).value - - assert value1 == "test-value" - - # Turn 2 - bot_state3 = ConversationState(storage) - await bot_state3.clear_state(turn_context) - await bot_state3.save_changes(turn_context) - - # Turn 3 - bot_state4 = ConversationState(storage) - value2 = ( - await bot_state4.create_property("test-name").get( - turn_context, lambda: TestPocoState(value="default-value") - ) - ).value - - assert value2, "default-value" - - async def test_bot_state_delete(self): - # pylint: disable=unnecessary-lambda - turn_context = TestUtilities.create_empty_context() - turn_context.activity.conversation = ConversationAccount(id="1234") - - storage = MemoryStorage({}) - - # Turn 0 - bot_state1 = ConversationState(storage) - ( - await bot_state1.create_property("test-name").get( - turn_context, lambda: TestPocoState() - ) - ).value = "test-value" - await bot_state1.save_changes(turn_context) - - # Turn 1 - bot_state2 = ConversationState(storage) - value1 = ( - await bot_state2.create_property("test-name").get( - turn_context, lambda: TestPocoState(value="default-value") - ) - ).value - - assert value1 == "test-value" - - # Turn 2 - bot_state3 = ConversationState(storage) - await bot_state3.delete(turn_context) - - # Turn 3 - bot_state4 = ConversationState(storage) - value2 = ( - await bot_state4.create_property("test-name").get( - turn_context, lambda: TestPocoState(value="default-value") - ) - ).value - - assert value2 == "default-value" - - async def test_bot_state_get(self): - # pylint: disable=unnecessary-lambda - turn_context = TestUtilities.create_empty_context() - turn_context.activity.conversation = ConversationAccount(id="1234") - - storage = MemoryStorage({}) - - conversation_state = ConversationState(storage) - ( - await conversation_state.create_property("test-name").get( - turn_context, lambda: TestPocoState() - ) - ).value = "test-value" - - result = conversation_state.get(turn_context) - - assert result["test-name"].value == "test-value" +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +from unittest.mock import MagicMock +import aiounittest + +from botbuilder.core import ( + BotState, + ConversationState, + MemoryStorage, + Storage, + StoreItem, + TurnContext, + UserState, +) +from botbuilder.core.adapters import TestAdapter +from botbuilder.schema import Activity, ConversationAccount + +from test_utilities import TestUtilities + +RECEIVED_MESSAGE = Activity(type="message", text="received") +STORAGE_KEY = "stateKey" + + +def cached_state(context, state_key): + cached = context.services.get(state_key) + return cached["state"] if cached is not None else None + + +def key_factory(context): + assert context is not None + return STORAGE_KEY + + +class BotStateForTest(BotState): + def __init__(self, storage: Storage): + super().__init__(storage, f"BotState:BotState") + + def get_storage_key(self, turn_context: TurnContext) -> str: + return f"botstate/{turn_context.activity.channel_id}/{turn_context.activity.conversation.id}/BotState" + + +class CustomState(StoreItem): + def __init__(self, custom_string: str = None, e_tag: str = "*"): + super().__init__(custom_string=custom_string, e_tag=e_tag) + + +class TestPocoState: + __test__ = False + + def __init__(self, value=None): + self.value = value + + +class TestBotState(aiounittest.AsyncTestCase): + storage = MemoryStorage() + adapter = TestAdapter() + context = TurnContext(adapter, RECEIVED_MESSAGE) + middleware = BotState(storage, key_factory) + + def test_state_empty_name(self): + # Arrange + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + + # Act + with self.assertRaises(TypeError) as _: + user_state.create_property("") + + def test_state_none_name(self): + # Arrange + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + + # Act + with self.assertRaises(TypeError) as _: + user_state.create_property(None) + + async def test_storage_not_called_no_changes(self): + """Verify storage not called when no changes are made""" + # Mock a storage provider, which counts read/writes + dictionary = {} + + async def mock_write_result(self): # pylint: disable=unused-argument + return + + async def mock_read_result(self): # pylint: disable=unused-argument + return {} + + mock_storage = MemoryStorage(dictionary) + mock_storage.write = MagicMock(side_effect=mock_write_result) + mock_storage.read = MagicMock(side_effect=mock_read_result) + + # Arrange + user_state = UserState(mock_storage) + context = TestUtilities.create_empty_context() + + # Act + property_a = user_state.create_property("property_a") + self.assertEqual(mock_storage.write.call_count, 0) + await user_state.save_changes(context) + await property_a.set(context, "hello") + self.assertEqual(mock_storage.read.call_count, 1) # Initial save bumps count + self.assertEqual(mock_storage.write.call_count, 0) # Initial save bumps count + await property_a.set(context, "there") + self.assertEqual( + mock_storage.write.call_count, 0 + ) # Set on property should not bump + await user_state.save_changes(context) + self.assertEqual(mock_storage.write.call_count, 1) # Explicit save should bump + value_a = await property_a.get(context) + self.assertEqual("there", value_a) + self.assertEqual(mock_storage.write.call_count, 1) # Gets should not bump + await user_state.save_changes(context) + self.assertEqual(mock_storage.write.call_count, 1) + await property_a.delete(context) # Delete alone no bump + self.assertEqual(mock_storage.write.call_count, 1) + await user_state.save_changes(context) # Save when dirty should bump + self.assertEqual(mock_storage.write.call_count, 2) + self.assertEqual(mock_storage.read.call_count, 1) + await user_state.save_changes(context) # Save not dirty should not bump + self.assertEqual(mock_storage.write.call_count, 2) + self.assertEqual(mock_storage.read.call_count, 1) + + async def test_state_set_no_load(self): + """Should be able to set a property with no Load""" + # Arrange + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + context = TestUtilities.create_empty_context() + + # Act + property_a = user_state.create_property("property_a") + await property_a.set(context, "hello") + + async def test_state_multiple_loads(self): + """Should be able to load multiple times""" + # Arrange + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + context = TestUtilities.create_empty_context() + + # Act + user_state.create_property("property_a") + await user_state.load(context) + await user_state.load(context) + + async def test_state_get_no_load_with_default(self): + """Should be able to get a property with no Load and default""" + # Arrange + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + context = TestUtilities.create_empty_context() + + # Act + property_a = user_state.create_property("property_a") + value_a = await property_a.get(context, lambda: "Default!") + self.assertEqual("Default!", value_a) + + async def test_state_get_no_load_no_default(self): + """Cannot get a string with no default set""" + # Arrange + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + context = TestUtilities.create_empty_context() + + # Act + property_a = user_state.create_property("property_a") + value_a = await property_a.get(context) + + # Assert + self.assertIsNone(value_a) + + async def test_state_poco_no_default(self): + """Cannot get a POCO with no default set""" + # Arrange + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + context = TestUtilities.create_empty_context() + + # Act + test_property = user_state.create_property("test") + value = await test_property.get(context) + + # Assert + self.assertIsNone(value) + + async def test_state_bool_no_default(self): + """Cannot get a bool with no default set""" + # Arange + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + context = TestUtilities.create_empty_context() + + # Act + test_property = user_state.create_property("test") + value = await test_property.get(context) + + # Assert + self.assertFalse(value) + + async def test_state_set_after_save(self): + """Verify setting property after save""" + # Arrange + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + context = TestUtilities.create_empty_context() + + # Act + property_a = user_state.create_property("property-a") + property_b = user_state.create_property("property-b") + + await user_state.load(context) + await property_a.set(context, "hello") + await property_b.set(context, "world") + await user_state.save_changes(context) + + await property_a.set(context, "hello2") + + async def test_state_multiple_save(self): + """Verify multiple saves""" + # Arrange + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + context = TestUtilities.create_empty_context() + + # Act + property_a = user_state.create_property("property-a") + property_b = user_state.create_property("property-b") + + await user_state.load(context) + await property_a.set(context, "hello") + await property_b.set(context, "world") + await user_state.save_changes(context) + + await property_a.set(context, "hello2") + await user_state.save_changes(context) + value_a = await property_a.get(context) + self.assertEqual("hello2", value_a) + + async def test_load_set_save(self): + # Arrange + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + context = TestUtilities.create_empty_context() + + # Act + property_a = user_state.create_property("property-a") + property_b = user_state.create_property("property-b") + + await user_state.load(context) + await property_a.set(context, "hello") + await property_b.set(context, "world") + await user_state.save_changes(context) + + # Assert + obj = dictionary["EmptyContext/users/[email protected]"] + self.assertEqual("hello", obj["property-a"]) + self.assertEqual("world", obj["property-b"]) + + async def test_load_set_save_twice(self): + # Arrange + dictionary = {} + context = TestUtilities.create_empty_context() + + # Act + user_state = UserState(MemoryStorage(dictionary)) + + property_a = user_state.create_property("property-a") + property_b = user_state.create_property("property-b") + property_c = user_state.create_property("property-c") + + await user_state.load(context) + await property_a.set(context, "hello") + await property_b.set(context, "world") + await property_c.set(context, "test") + await user_state.save_changes(context) + + # Assert + obj = dictionary["EmptyContext/users/[email protected]"] + self.assertEqual("hello", obj["property-a"]) + self.assertEqual("world", obj["property-b"]) + + # Act 2 + user_state2 = UserState(MemoryStorage(dictionary)) + + property_a2 = user_state2.create_property("property-a") + property_b2 = user_state2.create_property("property-b") + + await user_state2.load(context) + await property_a2.set(context, "hello-2") + await property_b2.set(context, "world-2") + await user_state2.save_changes(context) + + # Assert 2 + obj2 = dictionary["EmptyContext/users/[email protected]"] + self.assertEqual("hello-2", obj2["property-a"]) + self.assertEqual("world-2", obj2["property-b"]) + self.assertEqual("test", obj2["property-c"]) + + async def test_load_save_delete(self): + # Arrange + dictionary = {} + context = TestUtilities.create_empty_context() + + # Act + user_state = UserState(MemoryStorage(dictionary)) + + property_a = user_state.create_property("property-a") + property_b = user_state.create_property("property-b") + + await user_state.load(context) + await property_a.set(context, "hello") + await property_b.set(context, "world") + await user_state.save_changes(context) + + # Assert + obj = dictionary["EmptyContext/users/[email protected]"] + self.assertEqual("hello", obj["property-a"]) + self.assertEqual("world", obj["property-b"]) + + # Act 2 + user_state2 = UserState(MemoryStorage(dictionary)) + + property_a2 = user_state2.create_property("property-a") + property_b2 = user_state2.create_property("property-b") + + await user_state2.load(context) + await property_a2.set(context, "hello-2") + await property_b2.delete(context) + await user_state2.save_changes(context) + + # Assert 2 + obj2 = dictionary["EmptyContext/users/[email protected]"] + self.assertEqual("hello-2", obj2["property-a"]) + with self.assertRaises(KeyError) as _: + obj2["property-b"] # pylint: disable=pointless-statement + + async def test_state_use_bot_state_directly(self): + async def exec_test(context: TurnContext): + # pylint: disable=unnecessary-lambda + bot_state_manager = BotStateForTest(MemoryStorage()) + test_property = bot_state_manager.create_property("test") + + # read initial state object + await bot_state_manager.load(context) + + custom_state = await test_property.get(context, lambda: CustomState()) + + # this should be a 'CustomState' as nothing is currently stored in storage + assert isinstance(custom_state, CustomState) + + # amend property and write to storage + custom_state.custom_string = "test" + await bot_state_manager.save_changes(context) + + custom_state.custom_string = "asdfsadf" + + # read into context again + await bot_state_manager.load(context, True) + + custom_state = await test_property.get(context) + + # check object read from value has the correct value for custom_string + assert custom_state.custom_string == "test" + + adapter = TestAdapter(exec_test) + await adapter.send("start") + + async def test_user_state_bad_from_throws(self): + dictionary = {} + user_state = UserState(MemoryStorage(dictionary)) + context = TestUtilities.create_empty_context() + context.activity.from_property = None + test_property = user_state.create_property("test") + with self.assertRaises(AttributeError): + await test_property.get(context) + + async def test_conversation_state_bad_conversation_throws(self): + dictionary = {} + user_state = ConversationState(MemoryStorage(dictionary)) + context = TestUtilities.create_empty_context() + context.activity.conversation = None + test_property = user_state.create_property("test") + with self.assertRaises(AttributeError): + await test_property.get(context) + + async def test_clear_and_save(self): + # pylint: disable=unnecessary-lambda + turn_context = TestUtilities.create_empty_context() + turn_context.activity.conversation = ConversationAccount(id="1234") + + storage = MemoryStorage({}) + + # Turn 0 + bot_state1 = ConversationState(storage) + ( + await bot_state1.create_property("test-name").get( + turn_context, lambda: TestPocoState() + ) + ).value = "test-value" + await bot_state1.save_changes(turn_context) + + # Turn 1 + bot_state2 = ConversationState(storage) + value1 = ( + await bot_state2.create_property("test-name").get( + turn_context, lambda: TestPocoState(value="default-value") + ) + ).value + + assert value1 == "test-value" + + # Turn 2 + bot_state3 = ConversationState(storage) + await bot_state3.clear_state(turn_context) + await bot_state3.save_changes(turn_context) + + # Turn 3 + bot_state4 = ConversationState(storage) + value2 = ( + await bot_state4.create_property("test-name").get( + turn_context, lambda: TestPocoState(value="default-value") + ) + ).value + + assert value2, "default-value" + + async def test_bot_state_delete(self): + # pylint: disable=unnecessary-lambda + turn_context = TestUtilities.create_empty_context() + turn_context.activity.conversation = ConversationAccount(id="1234") + + storage = MemoryStorage({}) + + # Turn 0 + bot_state1 = ConversationState(storage) + ( + await bot_state1.create_property("test-name").get( + turn_context, lambda: TestPocoState() + ) + ).value = "test-value" + await bot_state1.save_changes(turn_context) + + # Turn 1 + bot_state2 = ConversationState(storage) + value1 = ( + await bot_state2.create_property("test-name").get( + turn_context, lambda: TestPocoState(value="default-value") + ) + ).value + + assert value1 == "test-value" + + # Turn 2 + bot_state3 = ConversationState(storage) + await bot_state3.delete(turn_context) + + # Turn 3 + bot_state4 = ConversationState(storage) + value2 = ( + await bot_state4.create_property("test-name").get( + turn_context, lambda: TestPocoState(value="default-value") + ) + ).value + + assert value2 == "default-value" + + async def test_bot_state_get(self): + # pylint: disable=unnecessary-lambda + turn_context = TestUtilities.create_empty_context() + turn_context.activity.conversation = ConversationAccount(id="1234") + + storage = MemoryStorage({}) + + conversation_state = ConversationState(storage) + ( + await conversation_state.create_property("test-name").get( + turn_context, lambda: TestPocoState() + ) + ).value = "test-value" + + result = conversation_state.get(turn_context) + + assert result["test-name"].value == "test-value"
Waterfall dialogs/tests aren't compatible with Python 3.8 ## Version 4.7 ## Describe the bug Two waterfall tests are failing when using Python 3.8 ## To Reproduce Steps to reproduce the behavior: 1. Install Python 3.8 2. Build Bot Builder Python and run the tests according to these instructions: https://github.com/microsoft/botbuilder-python/wiki/building-the-sdk 3. See failing tests ## Expected behavior Bot Builder Python should be compatible with the latest version of Python [bug]
2020-02-14T21:19:17
microsoft/botbuilder-python
747
microsoft__botbuilder-python-747
[ "743" ]
9a5e20add20febd7115f54506c15154ed922c212
diff --git a/libraries/botbuilder-core/botbuilder/core/re_escape.py b/libraries/botbuilder-core/botbuilder/core/re_escape.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-core/botbuilder/core/re_escape.py @@ -0,0 +1,25 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +# SPECIAL_CHARS +# closing ')', '}' and ']' +# '-' (a range in character set) +# '&', '~', (extended character set operations) +# '#' (comment) and WHITESPACE (ignored) in verbose mode +SPECIAL_CHARS_MAP = {i: "\\" + chr(i) for i in b"()[]{}?*+-|^$\\.&~# \t\n\r\v\f"} + + +def escape(pattern): + """ + Escape special characters in a string. + + This is a copy of the re.escape function in Python 3.8. This was done + because the 3.6.x version didn't escape in the same way and handling + bot names with regex characters in it would fail in TurnContext.remove_mention_text + without escaping the text. + """ + if isinstance(pattern, str): + return pattern.translate(SPECIAL_CHARS_MAP) + + pattern = str(pattern, "latin1") + return pattern.translate(SPECIAL_CHARS_MAP).encode("latin1") diff --git a/libraries/botbuilder-core/botbuilder/core/turn_context.py b/libraries/botbuilder-core/botbuilder/core/turn_context.py --- a/libraries/botbuilder-core/botbuilder/core/turn_context.py +++ b/libraries/botbuilder-core/botbuilder/core/turn_context.py @@ -13,6 +13,7 @@ Mention, ResourceResponse, ) +from .re_escape import escape class TurnContext: @@ -362,7 +363,7 @@ def remove_mention_text(activity: Activity, identifier: str) -> str: if mention.additional_properties["mentioned"]["id"] == identifier: mention_name_match = re.match( r"<at(.*)>(.*?)<\/at>", - re.escape(mention.additional_properties["text"]), + escape(mention.additional_properties["text"]), re.IGNORECASE, ) if mention_name_match:
diff --git a/libraries/botbuilder-core/tests/test_turn_context.py b/libraries/botbuilder-core/tests/test_turn_context.py --- a/libraries/botbuilder-core/tests/test_turn_context.py +++ b/libraries/botbuilder-core/tests/test_turn_context.py @@ -322,8 +322,8 @@ def test_should_remove_at_mention_from_activity(self): text = TurnContext.remove_recipient_mention(activity) - assert text, " test activity" - assert activity.text, " test activity" + assert text == " test activity" + assert activity.text == " test activity" def test_should_remove_at_mention_with_regex_characters(self): activity = Activity( @@ -343,8 +343,8 @@ def test_should_remove_at_mention_with_regex_characters(self): text = TurnContext.remove_recipient_mention(activity) - assert text, " test activity" - assert activity.text, " test activity" + assert text == " test activity" + assert activity.text == " test activity" async def test_should_send_a_trace_activity(self): context = TurnContext(SimpleAdapter(), ACTIVITY)
test_inspection_middleware fails on Python 3.6.8 Test: test_should_replicate_activity_data_to_listening_emulator_following_open_and_attach_with_at_mention This test passes on 3.7.6 and 3.8.1
2020-02-18T16:02:46
microsoft/botbuilder-python
824
microsoft__botbuilder-python-824
[ "548" ]
e85d9fa57f4d033d88973d2e658aba26f591e1bc
diff --git a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_adapter.py b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_adapter.py --- a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_adapter.py +++ b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_adapter.py @@ -138,12 +138,11 @@ async def continue_conversation( Sends a proactive message to a conversation. Call this method to proactively send a message to a conversation. Most _channels require a user to initiate a conversation with a bot before the bot can send activities to the user. - :param bot_id: The application ID of the bot. This parameter is ignored in - single tenant the Adpters (Console, Test, etc) but is critical to the BotFrameworkAdapter - which is multi-tenant aware. </param> - :param reference: A reference to the conversation to continue.</param> - :param callback: The method to call for the resulting bot turn.</param> - :param claims_identity: + :param bot_id: Unused for this override. + :param reference: A reference to the conversation to continue. + :param callback: The method to call for the resulting bot turn. + :param claims_identity: A ClaimsIdentity for the conversation. + :param audience: Unused for this override. """ if not reference: @@ -151,11 +150,19 @@ async def continue_conversation( if not callback: raise Exception("callback is required") - request = TurnContext.apply_conversation_reference( - conversation_reference_extension.get_continuation_activity(reference), - reference, - ) - context = TurnContext(self, request) + if claims_identity: + request = conversation_reference_extension.get_continuation_activity( + reference + ) + context = TurnContext(self, request) + context.turn_state[BotAdapter.BOT_IDENTITY_KEY] = claims_identity + context.turn_state[BotAdapter.BOT_CALLBACK_HANDLER_KEY] = callback + else: + request = TurnContext.apply_conversation_reference( + conversation_reference_extension.get_continuation_activity(reference), + reference, + ) + context = TurnContext(self, request) return await self.run_pipeline(context, callback)
[PORT] BotAdapter changes (made for custom adapter / skills compat) > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3148 #3147 - Added additional ContinueConversationAsync overload for custom adapters for skills compatibility. #3146 - Move 'BotIdentityKey' const to BotAdapter and made it public.
Custom adapters do not currently exist for Python - just requires move 'BotIdentityKey' const to BotAdapter and made it public for parity.
2020-03-04T22:25:19
microsoft/botbuilder-python
837
microsoft__botbuilder-python-837
[ "836" ]
61fe14f48be3174a8c4f46e8ad67e0717f22880b
diff --git a/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py b/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py --- a/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py +++ b/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py @@ -1478,12 +1478,18 @@ class TeamDetails(Model): :type name: str :param aad_group_id: Azure Active Directory (AAD) Group Id for the team. :type aad_group_id: str + :param channel_count: The count of channels in the team. + :type chanel_count: int + :param member_count: The count of members in the team. + :type member_count: int """ _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "aad_group_id": {"key": "aadGroupId", "type": "str"}, + "channel_count": {"key": "channelCount", "type": "int"}, + "member_count": {"key": "memberCount", "type": "int"}, } def __init__(self, **kwargs): @@ -1491,6 +1497,8 @@ def __init__(self, **kwargs): self.id = kwargs.get("id", None) self.name = kwargs.get("name", None) self.aad_group_id = kwargs.get("aad_group_id", None) + self.channel_count = kwargs.get("channel_count", None) + self.member_count = kwargs.get("member_count", None) class TeamInfo(Model): diff --git a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py --- a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py +++ b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py @@ -1736,21 +1736,36 @@ class TeamDetails(Model): :type name: str :param aad_group_id: Azure Active Directory (AAD) Group Id for the team. :type aad_group_id: str + :param channel_count: The count of channels in the team. + :type channel_count: int + :param member_count: The count of members in the team. + :type member_count: int """ _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, "aad_group_id": {"key": "aadGroupId", "type": "str"}, + "channel_count": {"key": "channelCount", "type": "int"}, + "member_count": {"key": "memberCount", "type": "int"}, } def __init__( - self, *, id: str = None, name: str = None, aad_group_id: str = None, **kwargs + self, + *, + id: str = None, + name: str = None, + aad_group_id: str = None, + member_count: int = None, + channel_count: int = None, + **kwargs ) -> None: super(TeamDetails, self).__init__(**kwargs) self.id = id self.name = name self.aad_group_id = aad_group_id + self.channel_count = channel_count + self.member_count = member_count class TeamInfo(Model):
[PORT] Add new fields and remove auto-generated text. > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3499 fixes: #3497 Changes: - Add ChannelCount and MemberCount to TeamDetails object - Remove auto-generated documentation - Move file out of the generated folder to make clear this is no longer auto-generated # Changed projects * Microsoft.Bot.Schema [parity with python]
2020-03-06T20:05:08
microsoft/botbuilder-python
860
microsoft__botbuilder-python-860
[ "859" ]
d282ea386b74f8c36ce0873cf9b85fb7da2aaa05
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_extensions.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_extensions.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_extensions.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_extensions.py @@ -30,7 +30,13 @@ async def run_dialog( if ( turn_context.activity.type == ActivityTypes.end_of_conversation and dialog_context.stack + and DialogExtensions.__is_eoc_coming_from_parent(turn_context) ): + remote_cancel_text = "Skill was canceled through an EndOfConversation activity from the parent." + await turn_context.send_trace_activity( + f"Extension {Dialog.__name__}.run_dialog", label=remote_cancel_text, + ) + await dialog_context.cancel_all_dialogs() else: # Process a reprompt event sent from the parent. @@ -75,3 +81,9 @@ async def run_dialog( results = await dialog_context.continue_dialog() if results.status == DialogTurnStatus.Empty: await dialog_context.begin_dialog(dialog.id) + + @staticmethod + def __is_eoc_coming_from_parent(turn_context: TurnContext) -> bool: + # To determine the direction we check callerId property which is set to the parent bot + # by the BotFrameworkHttpClient on outgoing requests. + return bool(turn_context.activity.caller_id) diff --git a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py --- a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py +++ b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py @@ -97,7 +97,7 @@ async def post_activity( ) activity.conversation.id = conversation_id activity.service_url = service_url - activity.caller_id = from_bot_id + activity.caller_id = f"urn:botframework:aadappid:{from_bot_id}" headers_dict = { "Content-type": "application/json; charset=utf-8",
[PORT] EoC should only be handled when coming from parent in RunAsync > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3540 Fixes #3541 Added check to only cancel dialogs in RunAsync when EoC comes from a parent bot (root or skill). The issue was that this affected part of the code was being triggered when a skill responds with an EoC to a caller (EoCs are routed back to the pipeline in SkillHandler). This PR also applies the urn format to CallerId as per [OBI Spec](https://github.com/microsoft/botframework-obi/blob/master/protocols/botframework-activity/botframework-activity.md#bot-calling-skill) # Changed projects * Microsoft.Bot.Builder.Dialogs * integration
2020-03-12T14:48:24
microsoft/botbuilder-python
886
microsoft__botbuilder-python-886
[ "878" ]
1d40a5754cc3b2db6538821673953bb5c1616399
diff --git a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py --- a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py +++ b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py @@ -115,8 +115,7 @@ async def post_activity( data = (await resp.read()).decode() content = json.loads(data) if data else None - if content: - return InvokeResponse(status=resp.status, body=content) + return InvokeResponse(status=resp.status, body=content) finally: # Restore activity properties.
SkillDialog not working for non-'expected replies' scenario ## Version 4.8.0 ## Describe the bug SkillDialog won't work out of the box for non expected-replies scenarios. ## To Reproduce Steps to reproduce the behavior: 1. Set up a root bot using skill dialog and a skill bot 2. Run both bots and initiate the SkillDialog 3. When the skill first comes back to the parent an error like the following should arise: ``` File "..path-to-botbuilder/botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/skills/skill_dialog.py", line 213, in _send_to_skill if not 200 <= response.status <= 299: AttributeError: 'NoneType' object has no attribute 'status' ``` ## Expected behavior The response get back to the parent without any problems ## Workaround If the skill bot is modified to always send some content in every successful response at the route handler level, the scenario should work. Example on how to do this for an aiohttp skill bot: ```python #This is how a typical message handler method could look like async def messages(req: Request) -> Response: # Main bot message handler. if "application/json" in req.headers["Content-Type"]: body = await req.json() else: return Response(status=415) activity = Activity().deserialize(body) auth_header = req.headers["Authorization"] if "Authorization" in req.headers else "" response = await ADAPTER.process_activity(activity, auth_header, BOT.on_turn) if response: return json_response(data=response.body, status=response.status) # THE FIX IS IN THE LINE BELOW return Response(status=201, body='{"foo":"bar"}'.encode("utf-8")) ``` **Alternative Workaround:** use expected replies as delivery method in the parent bot (SkillDialog). [bug]
2020-03-24T07:13:49
microsoft/botbuilder-python
888
microsoft__botbuilder-python-888
[ "845" ]
01fcbe9e4d60bfe1bd314e4481834e453284ca41
diff --git a/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py b/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py --- a/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py +++ b/libraries/botbuilder-core/botbuilder/core/show_typing_middleware.py @@ -1,8 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. - -import time -from functools import wraps +import asyncio from typing import Awaitable, Callable from botbuilder.schema import Activity, ActivityTypes @@ -11,38 +9,38 @@ from .turn_context import TurnContext -def delay(span=0.0): - def wrap(func): - @wraps(func) - async def delayed(): - time.sleep(span) - await func() - - return delayed - - return wrap - - class Timer: clear_timer = False - async def set_timeout(self, func, time): - is_invocation_cancelled = False - - @delay(time) + def set_timeout(self, func, span): async def some_fn(): # pylint: disable=function-redefined + await asyncio.sleep(span) if not self.clear_timer: await func() - await some_fn() - return is_invocation_cancelled + asyncio.ensure_future(some_fn()) def set_clear_timer(self): self.clear_timer = True class ShowTypingMiddleware(Middleware): + """ + When added, this middleware will send typing activities back to the user when a Message activity + is received to let them know that the bot has received the message and is working on the response. + You can specify a delay before the first typing activity is sent and then a frequency, which + determines how often another typing activity is sent. Typing activities will continue to be sent + until your bot sends another message back to the user. + """ + def __init__(self, delay: float = 0.5, period: float = 2.0): + """ + Initializes the middleware. + + :param delay: Delay in seconds for the first typing indicator to be sent. + :param period: Delay in seconds for subsequent typing indicators. + """ + if delay < 0: raise ValueError("Delay must be greater than or equal to zero") @@ -55,41 +53,43 @@ def __init__(self, delay: float = 0.5, period: float = 2.0): async def on_turn( self, context: TurnContext, logic: Callable[[TurnContext], Awaitable] ): - finished = False timer = Timer() - async def start_interval(context: TurnContext, delay: int, period: int): + def start_interval(context: TurnContext, delay, period): async def aux(): - if not finished: - typing_activity = Activity( - type=ActivityTypes.typing, - relates_to=context.activity.relates_to, - ) + typing_activity = Activity( + type=ActivityTypes.typing, relates_to=context.activity.relates_to, + ) - conversation_reference = TurnContext.get_conversation_reference( - context.activity - ) + conversation_reference = TurnContext.get_conversation_reference( + context.activity + ) - typing_activity = TurnContext.apply_conversation_reference( - typing_activity, conversation_reference - ) + typing_activity = TurnContext.apply_conversation_reference( + typing_activity, conversation_reference + ) - await context.adapter.send_activities(context, [typing_activity]) + asyncio.ensure_future( + context.adapter.send_activities(context, [typing_activity]) + ) - start_interval(context, period, period) + # restart the timer, with the 'period' value for the delay + timer.set_timeout(aux, period) - await timer.set_timeout(aux, delay) + # first time through we use the 'delay' value for the timer. + timer.set_timeout(aux, delay) def stop_interval(): - nonlocal finished - finished = True timer.set_clear_timer() + # if it's a message, start sending typing activities until the + # bot logic is done. if context.activity.type == ActivityTypes.message: - finished = False - await start_interval(context, self._delay, self._period) + start_interval(context, self._delay, self._period) + # call the bot logic result = await logic() + stop_interval() return result
diff --git a/libraries/botbuilder-core/tests/test_show_typing_middleware.py b/libraries/botbuilder-core/tests/test_show_typing_middleware.py --- a/libraries/botbuilder-core/tests/test_show_typing_middleware.py +++ b/libraries/botbuilder-core/tests/test_show_typing_middleware.py @@ -1,68 +1,67 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -import time -import aiounittest - -from botbuilder.core import ShowTypingMiddleware -from botbuilder.core.adapters import TestAdapter -from botbuilder.schema import ActivityTypes - - -class TestShowTypingMiddleware(aiounittest.AsyncTestCase): - async def test_should_automatically_send_a_typing_indicator(self): - async def aux(context): - time.sleep(0.600) - await context.send_activity(f"echo:{context.activity.text}") - - def assert_is_typing(activity, description): # pylint: disable=unused-argument - assert activity.type == ActivityTypes.typing - - adapter = TestAdapter(aux) - adapter.use(ShowTypingMiddleware()) - - step1 = await adapter.send("foo") - step2 = await step1.assert_reply(assert_is_typing) - step3 = await step2.assert_reply("echo:foo") - step4 = await step3.send("bar") - step5 = await step4.assert_reply(assert_is_typing) - await step5.assert_reply("echo:bar") - - async def test_should_not_automatically_send_a_typing_indicator_if_no_middleware( - self, - ): - async def aux(context): - await context.send_activity(f"echo:{context.activity.text}") - - adapter = TestAdapter(aux) - - step1 = await adapter.send("foo") - await step1.assert_reply("echo:foo") - - async def test_should_not_immediately_respond_with_message(self): - async def aux(context): - time.sleep(0.600) - await context.send_activity(f"echo:{context.activity.text}") - - def assert_is_not_message( - activity, description - ): # pylint: disable=unused-argument - assert activity.type != ActivityTypes.message - - adapter = TestAdapter(aux) - adapter.use(ShowTypingMiddleware()) - - step1 = await adapter.send("foo") - await step1.assert_reply(assert_is_not_message) - - async def test_should_immediately_respond_with_message_if_no_middleware(self): - async def aux(context): - await context.send_activity(f"echo:{context.activity.text}") - - def assert_is_message(activity, description): # pylint: disable=unused-argument - assert activity.type == ActivityTypes.message - - adapter = TestAdapter(aux) - - step1 = await adapter.send("foo") - await step1.assert_reply(assert_is_message) +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +import asyncio +import aiounittest + +from botbuilder.core import ShowTypingMiddleware +from botbuilder.core.adapters import TestAdapter +from botbuilder.schema import ActivityTypes + + +class TestShowTypingMiddleware(aiounittest.AsyncTestCase): + async def test_should_automatically_send_a_typing_indicator(self): + async def aux(context): + await asyncio.sleep(0.600) + await context.send_activity(f"echo:{context.activity.text}") + + def assert_is_typing(activity, description): # pylint: disable=unused-argument + assert activity.type == ActivityTypes.typing + + adapter = TestAdapter(aux) + adapter.use(ShowTypingMiddleware()) + + step1 = await adapter.send("foo") + step2 = await step1.assert_reply(assert_is_typing) + step3 = await step2.assert_reply("echo:foo") + step4 = await step3.send("bar") + step5 = await step4.assert_reply(assert_is_typing) + await step5.assert_reply("echo:bar") + + async def test_should_not_automatically_send_a_typing_indicator_if_no_middleware( + self, + ): + async def aux(context): + await context.send_activity(f"echo:{context.activity.text}") + + adapter = TestAdapter(aux) + + step1 = await adapter.send("foo") + await step1.assert_reply("echo:foo") + + async def test_should_not_immediately_respond_with_message(self): + async def aux(context): + await asyncio.sleep(0.600) + await context.send_activity(f"echo:{context.activity.text}") + + def assert_is_not_message( + activity, description + ): # pylint: disable=unused-argument + assert activity.type != ActivityTypes.message + + adapter = TestAdapter(aux) + adapter.use(ShowTypingMiddleware()) + + step1 = await adapter.send("foo") + await step1.assert_reply(assert_is_not_message) + + async def test_should_immediately_respond_with_message_if_no_middleware(self): + async def aux(context): + await context.send_activity(f"echo:{context.activity.text}") + + def assert_is_message(activity, description): # pylint: disable=unused-argument + assert activity.type == ActivityTypes.message + + adapter = TestAdapter(aux) + + step1 = await adapter.send("foo") + await step1.assert_reply(assert_is_message)
[bug] ShowTypingMiddleware middleware in a python bot not functioning ## Version `botbuilder-core 4.7.1` `botbuilder-schema 4.7.1` ## Describe the bug ``` python #app.py ADAPTER = BotFrameworkAdapter(SETTINGS) # show typing indicator on long activities ADAPTER.use(ShowTypingMiddleware(delay=0.5, period=2.0)) ``` ``` python #bot.py ... async def on_message_activity(self, turn_context: TurnContext): if turn_context.activity.text == "middleware": await asyncio.sleep(10) # mock getting some data await turn_context.send_activity("done") ... ``` ## Expected behavior I expect that calling the middleware - shows a TI for activities taking longer than .5 seconds - repeat sending a TI to the client every 2 seconds ## Actual results : - TI is sent one time only - no repeat TI are sent - a runtime warning is shown: ``` c:\develop\x\pybot1\.venv\lib\site-packages\botbuilder\core\show_typing_middleware.py:79: RuntimeWarning: coroutine 'ShowTypingMiddleware.on_turn.<locals>.start_interval' was never awaited start_interval(context, period, period) RuntimeWarning: Enable tracemalloc to get the object allocation traceback ``` In the emulator log it is clear that only one TI indicator is sent , and no repeats are to be seen ``` [16:55:12]<- messageYou said 'middleware' [16:55:12]POST200conversations.:conversationId.activities.:activityId [16:55:12]POST201directline.conversations.:conversationId.activities [16:55:43]-> messagemiddleware [16:55:44]<- typing [16:55:44]POST200conversations.:conversationId.activities.:activityId [16:55:54]<- messagedone [16:55:54]POST200conversations.:conversationId.activities.:activityId [16:55:54]POST201directline.conversations.:conversationId.activities ``` ## Additional context also see Question on [SO](https://stackoverflow.com/posts/60467080/edit)
2020-03-24T13:43:14
microsoft/botbuilder-python
889
microsoft__botbuilder-python-889
[ "734" ]
2305e2077528ef66ad3d9a927984b94d66e4a25d
diff --git a/libraries/botbuilder-core/botbuilder/core/activity_handler.py b/libraries/botbuilder-core/botbuilder/core/activity_handler.py --- a/libraries/botbuilder-core/botbuilder/core/activity_handler.py +++ b/libraries/botbuilder-core/botbuilder/core/activity_handler.py @@ -80,6 +80,8 @@ async def on_turn(self, turn_context: TurnContext): ) elif turn_context.activity.type == ActivityTypes.end_of_conversation: await self.on_end_of_conversation_activity(turn_context) + elif turn_context.activity.type == ActivityTypes.typing: + await self.on_typing_activity(turn_context) else: await self.on_unrecognized_activity_type(turn_context) @@ -346,6 +348,19 @@ async def on_end_of_conversation_activity( # pylint: disable=unused-argument """ return + async def on_typing_activity( # pylint: disable=unused-argument + self, turn_context: TurnContext + ): + """ + Override this in a derived class to provide logic specific to + ActivityTypes.typing activities, such as the conversational logic. + + :param turn_context: The context object for this turn + :type turn_context: :class:`botbuilder.core.TurnContext` + :returns: A task that represents the work queued to execute + """ + return + async def on_unrecognized_activity_type( # pylint: disable=unused-argument self, turn_context: TurnContext ):
diff --git a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py --- a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py +++ b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py @@ -57,6 +57,14 @@ async def on_event(self, turn_context: TurnContext): self.record.append("on_event") return await super().on_event(turn_context) + async def on_end_of_conversation_activity(self, turn_context: TurnContext): + self.record.append("on_end_of_conversation_activity") + return await super().on_end_of_conversation_activity(turn_context) + + async def on_typing_activity(self, turn_context: TurnContext): + self.record.append("on_typing_activity") + return await super().on_typing_activity(turn_context) + async def on_unrecognized_activity_type(self, turn_context: TurnContext): self.record.append("on_unrecognized_activity_type") return await super().on_unrecognized_activity_type(turn_context) @@ -724,3 +732,27 @@ async def test_on_teams_task_module_submit(self): assert len(bot.record) == 2 assert bot.record[0] == "on_invoke_activity" assert bot.record[1] == "on_teams_task_module_submit" + + async def test_on_end_of_conversation_activity(self): + activity = Activity(type=ActivityTypes.end_of_conversation) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + assert len(bot.record) == 1 + assert bot.record[0] == "on_end_of_conversation_activity" + + async def test_typing_activity(self): + activity = Activity(type=ActivityTypes.typing) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + assert len(bot.record) == 1 + assert bot.record[0] == "on_typing_activity" diff --git a/libraries/botbuilder-core/tests/test_activity_handler.py b/libraries/botbuilder-core/tests/test_activity_handler.py --- a/libraries/botbuilder-core/tests/test_activity_handler.py +++ b/libraries/botbuilder-core/tests/test_activity_handler.py @@ -59,6 +59,14 @@ async def on_event(self, turn_context: TurnContext): self.record.append("on_event") return await super().on_event(turn_context) + async def on_end_of_conversation_activity(self, turn_context: TurnContext): + self.record.append("on_end_of_conversation_activity") + return await super().on_end_of_conversation_activity(turn_context) + + async def on_typing_activity(self, turn_context: TurnContext): + self.record.append("on_typing_activity") + return await super().on_typing_activity(turn_context) + async def on_unrecognized_activity_type(self, turn_context: TurnContext): self.record.append("on_unrecognized_activity_type") return await super().on_unrecognized_activity_type(turn_context) @@ -172,3 +180,29 @@ async def test_invoke_should_not_match(self): assert len(bot.record) == 1 assert bot.record[0] == "on_invoke_activity" assert adapter.activity.value.status == int(HTTPStatus.NOT_IMPLEMENTED) + + async def test_on_end_of_conversation_activity(self): + activity = Activity(type=ActivityTypes.end_of_conversation) + + adapter = TestInvokeAdapter() + turn_context = TurnContext(adapter, activity) + + # Act + bot = TestingActivityHandler() + await bot.on_turn(turn_context) + + assert len(bot.record) == 1 + assert bot.record[0] == "on_end_of_conversation_activity" + + async def test_typing_activity(self): + activity = Activity(type=ActivityTypes.typing) + + adapter = TestInvokeAdapter() + turn_context = TurnContext(adapter, activity) + + # Act + bot = TestingActivityHandler() + await bot.on_turn(turn_context) + + assert len(bot.record) == 1 + assert bot.record[0] == "on_typing_activity"
[PORT] add typing activity to activityhandler > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3384 # Changed projects * Microsoft.Bot.Builder * Microsoft.Bot.Builder.Tests
2020-03-24T14:11:58
microsoft/botbuilder-python
890
microsoft__botbuilder-python-890
[ "476" ]
3840f9943d42feceb38a15507e6a116f79f9ac7d
diff --git a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py --- a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py +++ b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py @@ -132,7 +132,7 @@ class FileConsentCardResponse(Model): :param action: The action the user took. Possible values include: 'accept', 'decline' - :type action: str or ~botframework.connector.teams.models.enum + :type action: str :param context: The context associated with the action. :type context: object :param upload_info: If the user accepted the file, contains information @@ -346,7 +346,7 @@ class MessageActionsPayloadBody(Model): :param content_type: Type of the content. Possible values include: 'html', 'text' - :type content_type: str or ~botframework.connector.teams.models.enum + :type content_type: str :param content: The content of the body. :type content: str """ @@ -463,7 +463,7 @@ class MessageActionsPayloadReaction(Model): :param reaction_type: The type of reaction given to the message. Possible values include: 'like', 'heart', 'laugh', 'surprised', 'sad', 'angry' - :type reaction_type: str or ~botframework.connector.teams.models.enum + :type reaction_type: str :param created_date_time: Timestamp of when the user reacted to the message. :type created_date_time: str @@ -491,7 +491,7 @@ class MessageActionsPayloadUser(Model): :param user_identity_type: The identity type of the user. Possible values include: 'aadUser', 'onPremiseAadUser', 'anonymousGuest', 'federatedUser' - :type user_identity_type: str or ~botframework.connector.teams.models.enum + :type user_identity_type: str :param id: The id of the user. :type id: str :param display_name: The plaintext display name of the user. @@ -528,7 +528,7 @@ class MessageActionsPayload(Model): :type reply_to_id: str :param message_type: Type of message - automatically set to message. Possible values include: 'message' - :type message_type: str or ~botframework.connector.teams.models.enum + :type message_type: str :param created_date_time: Timestamp of when the message was created. :type created_date_time: str :param last_modified_date_time: Timestamp of when the message was edited @@ -543,7 +543,7 @@ class MessageActionsPayload(Model): :type summary: str :param importance: The importance of the message. Possible values include: 'normal', 'high', 'urgent' - :type importance: str or ~botframework.connector.teams.models.enum + :type importance: str :param locale: Locale of the message set by the client. :type locale: str :param from_property: Sender of the message. @@ -639,7 +639,7 @@ class MessagingExtensionAction(TaskModuleRequest): :type command_id: str :param command_context: The context from which the command originates. Possible values include: 'message', 'compose', 'commandbox' - :type command_context: str or ~botframework.connector.teams.models.enum + :type command_context: str :param bot_message_preview_action: Bot message preview action taken by user. Possible values include: 'edit', 'send' :type bot_message_preview_action: str or @@ -864,10 +864,10 @@ class MessagingExtensionResult(Model): :param attachment_layout: Hint for how to deal with multiple attachments. Possible values include: 'list', 'grid' - :type attachment_layout: str or ~botframework.connector.teams.models.enum + :type attachment_layout: str :param type: The type of the result. Possible values include: 'result', 'auth', 'config', 'message', 'botMessagePreview' - :type type: str or ~botframework.connector.teams.models.enum + :type type: str :param attachments: (Only when type is result) Attachments :type attachments: list[~botframework.connector.teams.models.MessagingExtensionAttachment] @@ -1002,7 +1002,7 @@ class O365ConnectorCardInputBase(Model): :param type: Input type name. Possible values include: 'textInput', 'dateInput', 'multichoiceInput' - :type type: str or ~botframework.connector.teams.models.enum + :type type: str :param id: Input Id. It must be unique per entire O365 connector card. :type id: str :param is_required: Define if this input is a required field. Default @@ -1045,7 +1045,7 @@ class O365ConnectorCardActionBase(Model): :param type: Type of the action. Possible values include: 'ViewAction', 'OpenUri', 'HttpPOST', 'ActionCard' - :type type: str or ~botframework.connector.teams.models.enum + :type type: str :param name: Name of the action that will be used as button title :type name: str :param id: Action Id @@ -1072,7 +1072,7 @@ class O365ConnectorCardActionCard(O365ConnectorCardActionBase): :param type: Type of the action. Possible values include: 'ViewAction', 'OpenUri', 'HttpPOST', 'ActionCard' - :type type: str or ~botframework.connector.teams.models.enum + :type type: str :param name: Name of the action that will be used as button title :type name: str :param id: Action Id @@ -1141,7 +1141,7 @@ class O365ConnectorCardDateInput(O365ConnectorCardInputBase): :param type: Input type name. Possible values include: 'textInput', 'dateInput', 'multichoiceInput' - :type type: str or ~botframework.connector.teams.models.enum + :type type: str :param id: Input Id. It must be unique per entire O365 connector card. :type id: str :param is_required: Define if this input is a required field. Default @@ -1212,7 +1212,7 @@ class O365ConnectorCardHttpPOST(O365ConnectorCardActionBase): :param type: Type of the action. Possible values include: 'ViewAction', 'OpenUri', 'HttpPOST', 'ActionCard' - :type type: str or ~botframework.connector.teams.models.enum + :type type: str :param name: Name of the action that will be used as button title :type name: str :param id: Action Id @@ -1262,7 +1262,7 @@ class O365ConnectorCardMultichoiceInput(O365ConnectorCardInputBase): :param type: Input type name. Possible values include: 'textInput', 'dateInput', 'multichoiceInput' - :type type: str or ~botframework.connector.teams.models.enum + :type type: str :param id: Input Id. It must be unique per entire O365 connector card. :type id: str :param is_required: Define if this input is a required field. Default @@ -1278,7 +1278,7 @@ class O365ConnectorCardMultichoiceInput(O365ConnectorCardInputBase): list[~botframework.connector.teams.models.O365ConnectorCardMultichoiceInputChoice] :param style: Choice item rendering style. Default value is 'compact'. Possible values include: 'compact', 'expanded' - :type style: str or ~botframework.connector.teams.models.enum + :type style: str :param is_multi_select: Define if this input field allows multiple selections. Default value is false. :type is_multi_select: bool @@ -1349,7 +1349,7 @@ class O365ConnectorCardOpenUri(O365ConnectorCardActionBase): :param type: Type of the action. Possible values include: 'ViewAction', 'OpenUri', 'HttpPOST', 'ActionCard' - :type type: str or ~botframework.connector.teams.models.enum + :type type: str :param name: Name of the action that will be used as button title :type name: str :param id: Action Id @@ -1380,7 +1380,7 @@ class O365ConnectorCardOpenUriTarget(Model): :param os: Target operating system. Possible values include: 'default', 'iOS', 'android', 'windows' - :type os: str or ~botframework.connector.teams.models.enum + :type os: str :param uri: Target url :type uri: str """ @@ -1481,7 +1481,7 @@ class O365ConnectorCardTextInput(O365ConnectorCardInputBase): :param type: Input type name. Possible values include: 'textInput', 'dateInput', 'multichoiceInput' - :type type: str or ~botframework.connector.teams.models.enum + :type type: str :param id: Input Id. It must be unique per entire O365 connector card. :type id: str :param is_required: Define if this input is a required field. Default @@ -1538,7 +1538,7 @@ class O365ConnectorCardViewAction(O365ConnectorCardActionBase): :param type: Type of the action. Possible values include: 'ViewAction', 'OpenUri', 'HttpPOST', 'ActionCard' - :type type: str or ~botframework.connector.teams.models.enum + :type type: str :param name: Name of the action that will be used as button title :type name: str :param id: Action Id @@ -1586,7 +1586,7 @@ class TaskModuleResponseBase(Model): :param type: Choice of action options when responding to the task/submit message. Possible values include: 'message', 'continue' - :type type: str or ~botframework.connector.teams.models.enum + :type type: str """ _attribute_map = { @@ -1601,9 +1601,6 @@ def __init__(self, *, type=None, **kwargs) -> None: class TaskModuleContinueResponse(TaskModuleResponseBase): """Task Module Response with continue action. - :param type: Choice of action options when responding to the task/submit - message. Possible values include: 'message', 'continue' - :type type: str or ~botframework.connector.teams.models.enum :param value: The JSON for the Adaptive card to appear in the task module. :type value: ~botframework.connector.teams.models.TaskModuleTaskInfo """ @@ -1613,17 +1610,14 @@ class TaskModuleContinueResponse(TaskModuleResponseBase): "value": {"key": "value", "type": "TaskModuleTaskInfo"}, } - def __init__(self, *, type=None, value=None, **kwargs) -> None: - super(TaskModuleContinueResponse, self).__init__(type=type, **kwargs) + def __init__(self, *, value=None, **kwargs) -> None: + super(TaskModuleContinueResponse, self).__init__(type="continue", **kwargs) self.value = value class TaskModuleMessageResponse(TaskModuleResponseBase): """Task Module response with message action. - :param type: Choice of action options when responding to the task/submit - message. Possible values include: 'message', 'continue' - :type type: str or ~botframework.connector.teams.models.enum :param value: Teams will display the value of value in a popup message box. :type value: str @@ -1634,8 +1628,8 @@ class TaskModuleMessageResponse(TaskModuleResponseBase): "value": {"key": "value", "type": "str"}, } - def __init__(self, *, type=None, value: str = None, **kwargs) -> None: - super(TaskModuleMessageResponse, self).__init__(type=type, **kwargs) + def __init__(self, *, value: str = None, **kwargs) -> None: + super(TaskModuleMessageResponse, self).__init__(type="message", **kwargs) self.value = value
[Teams] Should set the types for TaskModuleContinueResponse and TaskModuleMessageResponse ## Version master ## Describe the bug [TaskModuleContinueResponse](https://github.com/microsoft/botbuilder-python/blob/master/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py#L1316) can never have a type other than 'continue' [TaskModuleMessageResponse](https://github.com/microsoft/botbuilder-python/blob/master/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py#L1336) can never have a type other than 'message' [bug]
2020-03-24T16:05:12
microsoft/botbuilder-python
903
microsoft__botbuilder-python-903
[ "710" ]
6d42337020a88c54f544ddc67b7bd189105f0de7
diff --git a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py --- a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py +++ b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py @@ -18,8 +18,9 @@ from botframework.connector.auth import ( ChannelProvider, CredentialProvider, - GovernmentConstants, MicrosoftAppCredentials, + AppCredentials, + MicrosoftGovernmentAppCredentials, ) @@ -146,27 +147,26 @@ async def post_buffered_activity( async def _get_app_credentials( self, app_id: str, oauth_scope: str - ) -> MicrosoftAppCredentials: + ) -> AppCredentials: if not app_id: - return MicrosoftAppCredentials(None, None) + return MicrosoftAppCredentials.empty() + # in the cache? cache_key = f"{app_id}{oauth_scope}" app_credentials = BotFrameworkHttpClient._APP_CREDENTIALS_CACHE.get(cache_key) - if app_credentials: return app_credentials + # create a new AppCredentials app_password = await self._credential_provider.get_app_password(app_id) - app_credentials = MicrosoftAppCredentials( - app_id, app_password, oauth_scope=oauth_scope + + app_credentials = ( + MicrosoftGovernmentAppCredentials(app_id, app_password, scope=oauth_scope) + if self._credential_provider and self._channel_provider.is_government() + else MicrosoftAppCredentials(app_id, app_password, oauth_scope=oauth_scope) ) - if self._channel_provider and self._channel_provider.is_government(): - app_credentials.oauth_endpoint = ( - GovernmentConstants.TO_CHANNEL_FROM_BOT_LOGIN_URL - ) - app_credentials.oauth_scope = ( - GovernmentConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE - ) + # put it in the cache BotFrameworkHttpClient._APP_CREDENTIALS_CACHE[cache_key] = app_credentials + return app_credentials diff --git a/libraries/botframework-connector/botframework/connector/auth/microsoft_government_app_credentials.py b/libraries/botframework-connector/botframework/connector/auth/microsoft_government_app_credentials.py --- a/libraries/botframework-connector/botframework/connector/auth/microsoft_government_app_credentials.py +++ b/libraries/botframework-connector/botframework/connector/auth/microsoft_government_app_credentials.py @@ -14,10 +14,13 @@ def __init__( app_id: str, app_password: str, channel_auth_tenant: str = None, - scope: str = GovernmentConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE, + scope: str = None, ): super().__init__(app_id, app_password, channel_auth_tenant, scope) self.oauth_endpoint = GovernmentConstants.TO_CHANNEL_FROM_BOT_LOGIN_URL + self.oauth_scope = ( + scope if scope else GovernmentConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE + ) @staticmethod def empty():
[PORT] Updated MicrosoftGovernmentAppCredentials to support Skills in Azure Gov > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3353 Fixes https://github.com/microsoft/botbuilder-dotnet/issues/3233 Added constructor to MicrosoftGovernmentAppCredentials that takes OAuthScope to support skills in gov. Updated BotFrameworkHttpClient and BotFrameworkAdapter to pass the OAuthScope to MicrosoftGovernmentAppCredentials Added SimpleBotToBot functional test for testing. Added Microsoft.Bot.Framework.Skills.sln to load skills test projects. # Changed projects * Microsoft.Bot.Builder * Microsoft.Bot.Connector * integration * Microsoft.Bot.Connector.Tests [Skills]
Blocked by lack of Gov support for Python. Most of these changes have already been made. Excluding the functional tests which Python has limited support for right now. BotFrameworkHttpClient._get_app_credentials might be doing the correct thing. Needs to be double checked, and switch to using MicrosoftGovernmentAppCredentials.
2020-04-01T13:33:08
microsoft/botbuilder-python
924
microsoft__botbuilder-python-924
[ "788" ]
9fed14f74434048836a302a91aa649063a29e8e9
diff --git a/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py b/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py --- a/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py +++ b/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py @@ -160,15 +160,21 @@ async def fill_receive_event_properties( BotTelemetryClient.track_event method for the BotMessageReceived event. """ properties = { - TelemetryConstants.FROM_ID_PROPERTY: activity.from_property.id, + TelemetryConstants.FROM_ID_PROPERTY: activity.from_property.id + if activity.from_property + else None, TelemetryConstants.CONVERSATION_NAME_PROPERTY: activity.conversation.name, TelemetryConstants.LOCALE_PROPERTY: activity.locale, TelemetryConstants.RECIPIENT_ID_PROPERTY: activity.recipient.id, - TelemetryConstants.RECIPIENT_NAME_PROPERTY: activity.from_property.name, + TelemetryConstants.RECIPIENT_NAME_PROPERTY: activity.recipient.name, } if self.log_personal_information: - if activity.from_property.name and activity.from_property.name.strip(): + if ( + activity.from_property + and activity.from_property.name + and activity.from_property.name.strip() + ): properties[ TelemetryConstants.FROM_NAME_PROPERTY ] = activity.from_property.name
diff --git a/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py b/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py --- a/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py +++ b/libraries/botbuilder-core/botbuilder/core/adapters/test_adapter.py @@ -7,6 +7,7 @@ import asyncio import inspect +import uuid from datetime import datetime from uuid import uuid4 from typing import Awaitable, Coroutine, Dict, List, Callable, Union @@ -215,6 +216,19 @@ async def continue_conversation( reference, callback, bot_id, claims_identity, audience ) + async def create_conversation( + self, channel_id: str, callback: Callable # pylint: disable=unused-argument + ): + self.activity_buffer.clear() + update = Activity( + type=ActivityTypes.conversation_update, + members_added=[], + members_removed=[], + conversation=ConversationAccount(id=str(uuid.uuid4())), + ) + context = TurnContext(self, update) + return await callback(context) + async def receive_activity(self, activity): """ INTERNAL: called by a `TestFlow` instance to simulate a user sending a message to the bot. diff --git a/libraries/botbuilder-core/tests/test_telemetry_middleware.py b/libraries/botbuilder-core/tests/test_telemetry_middleware.py --- a/libraries/botbuilder-core/tests/test_telemetry_middleware.py +++ b/libraries/botbuilder-core/tests/test_telemetry_middleware.py @@ -3,6 +3,7 @@ # pylint: disable=line-too-long,missing-docstring,unused-variable import copy +import uuid from typing import Dict from unittest.mock import Mock import aiounittest @@ -28,6 +29,47 @@ async def test_create_middleware(self): my_logger = TelemetryLoggerMiddleware(telemetry, True) assert my_logger + async def test_do_not_throw_on_null_from(self): + telemetry = Mock() + my_logger = TelemetryLoggerMiddleware(telemetry, False) + + adapter = TestAdapter( + template_or_conversation=Activity( + channel_id="test", + recipient=ChannelAccount(id="bot", name="Bot"), + conversation=ConversationAccount(id=str(uuid.uuid4())), + ) + ) + adapter.use(my_logger) + + async def send_proactive(context: TurnContext): + await context.send_activity("proactive") + + async def logic(context: TurnContext): + await adapter.create_conversation( + context.activity.channel_id, send_proactive, + ) + + adapter.logic = logic + + test_flow = TestFlow(None, adapter) + await test_flow.send("foo") + await test_flow.assert_reply("proactive") + + telemetry_calls = [ + ( + TelemetryLoggerConstants.BOT_MSG_RECEIVE_EVENT, + { + "fromId": None, + "conversationName": None, + "locale": None, + "recipientId": "bot", + "recipientName": "Bot", + }, + ), + ] + self.assert_telemetry_calls(telemetry, telemetry_calls) + async def test_should_send_receive(self): telemetry = Mock() my_logger = TelemetryLoggerMiddleware(telemetry, True) @@ -55,7 +97,7 @@ async def logic(context: TurnContext): "conversationName": None, "locale": None, "recipientId": "bot", - "recipientName": "user", + "recipientName": "Bot", }, ), ( @@ -76,7 +118,7 @@ async def logic(context: TurnContext): "conversationName": None, "locale": None, "recipientId": "bot", - "recipientName": "user", + "recipientName": "Bot", "fromName": "user", }, ), @@ -147,7 +189,7 @@ async def process(context: TurnContext) -> None: "conversationName": None, "locale": None, "recipientId": "bot", - "recipientName": "user", + "recipientName": "Bot", }, ), ( @@ -169,7 +211,7 @@ async def process(context: TurnContext) -> None: "conversationName": None, "locale": None, "recipientId": "bot", - "recipientName": "user", + "recipientName": "Bot", "fromName": "user", }, ),
[PORT] Fix errors when From is null in telemetry > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3436 Fixes: #3395 If `TelemetryLoggerMiddleware` is used and then `CreateConversationAsync()` is called, there are cases where `Activity.From` will be null, which causes things like this to throw: ```csharp { TelemetryConstants.FromIdProperty, activity.From.Id }, ``` **Changes**: Adds a few null-conditional operators, where appropriate. **Testing**: Added one test which calls `CreateConversationAsync()` while ensuring the `Activity.From` is null. # Changed projects * Microsoft.Bot.Builder * integration * Microsoft.Bot.Builder.Tests
2020-04-08T20:53:02
microsoft/botbuilder-python
962
microsoft__botbuilder-python-962
[ "950" ]
5c38ab5fede81d06df3ef5b85ed4bbb50a62590f
diff --git a/libraries/botframework-connector/botframework/connector/auth/certificate_app_credentials.py b/libraries/botframework-connector/botframework/connector/auth/certificate_app_credentials.py --- a/libraries/botframework-connector/botframework/connector/auth/certificate_app_credentials.py +++ b/libraries/botframework-connector/botframework/connector/auth/certificate_app_credentials.py @@ -23,7 +23,20 @@ def __init__( certificate_private_key: str, channel_auth_tenant: str = None, oauth_scope: str = None, + certificate_public: str = None, ): + """ + AppCredentials implementation using a certificate. + + :param app_id: + :param certificate_thumbprint: + :param certificate_private_key: + :param channel_auth_tenant: + :param oauth_scope: + :param certificate_public: public_certificate (optional) is public key certificate which will be sent + through ‘x5c’ JWT header only for subject name and issuer authentication to support cert auto rolls. + """ + # super will set proper scope and endpoint. super().__init__( app_id=app_id, @@ -35,6 +48,7 @@ def __init__( self.app = None self.certificate_thumbprint = certificate_thumbprint self.certificate_private_key = certificate_private_key + self.certificate_public = certificate_public def get_access_token(self, force_refresh: bool = False) -> str: """ @@ -63,6 +77,9 @@ def __get_msal_app(self): client_credential={ "thumbprint": self.certificate_thumbprint, "private_key": self.certificate_private_key, + "public_certificate": self.certificate_public + if self.certificate_public + else None, }, ) diff --git a/libraries/botframework-connector/setup.py b/libraries/botframework-connector/setup.py --- a/libraries/botframework-connector/setup.py +++ b/libraries/botframework-connector/setup.py @@ -12,7 +12,7 @@ "PyJWT==1.5.3", "botbuilder-schema>=4.7.1", "adal==1.2.1", - "msal==1.1.0", + "msal==1.2.0", ] root = os.path.abspath(os.path.dirname(__file__))
[PORT] [Certificate Authentication] Expose sendX5c parameter > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3741 This parameter enables application developers to achieve easy certificates roll-over in Azure AD: setting this parameter to true will send the public certificate to Azure AD along with the token request, so that Azure AD can use it to validate the subject name based on a trusted issuer policy. This saves the application admin from the need to explicitly manage the certificate rollover (either via portal or powershell/CLI operation) # Changed projects * Microsoft.Bot.Connector [R9,authentication]
2020-04-17T18:06:04
microsoft/botbuilder-python
963
microsoft__botbuilder-python-963
[ "937" ]
20a2b23f9d9dbae99fe2af8476431cb2c5a846e3
diff --git a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py --- a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py +++ b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py @@ -39,15 +39,19 @@ class AppBasedLinkQuery(Model): :param url: Url queried by user :type url: str + :param state: The magic code for OAuth Flow + :type state: str """ _attribute_map = { "url": {"key": "url", "type": "str"}, + "state": {"key": "state", "type": "str"}, } - def __init__(self, *, url: str = None, **kwargs) -> None: + def __init__(self, *, url: str = None, state: str = None, **kwargs) -> None: super(AppBasedLinkQuery, self).__init__(**kwargs) self.url = url + self.state = state class ChannelInfo(Model):
[PORT] Add state to AppBasedLinkQuery for OAuth flow > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3732 Fixes: #3429 # Changed projects * Microsoft.Bot.Schema
2020-04-17T18:18:47
microsoft/botbuilder-python
976
microsoft__botbuilder-python-976
[ "922" ]
c04ecacb22c1f4b43a671fe2f1e4782218391975
diff --git a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py --- a/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py +++ b/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_client.py @@ -14,6 +14,7 @@ ExpectedReplies, ConversationReference, ConversationAccount, + ChannelAccount, ) from botframework.connector.auth import ( ChannelProvider, @@ -74,6 +75,7 @@ async def post_activity( original_conversation_id = activity.conversation.id original_service_url = activity.service_url original_relates_to = activity.relates_to + original_recipient = activity.recipient try: activity.relates_to = ConversationReference( @@ -94,30 +96,38 @@ async def post_activity( ) activity.conversation.id = conversation_id activity.service_url = service_url + if not activity.recipient: + activity.recipient = ChannelAccount() - headers_dict = { - "Content-type": "application/json; charset=utf-8", - } - if token: - headers_dict.update( - {"Authorization": f"Bearer {token}",} - ) - - json_content = json.dumps(activity.serialize()) - resp = await self._session.post( - to_url, data=json_content.encode("utf-8"), headers=headers_dict, - ) - resp.raise_for_status() - data = (await resp.read()).decode() - content = json.loads(data) if data else None + status, content = await self._post_content(to_url, token, activity) - return InvokeResponse(status=resp.status, body=content) + return InvokeResponse(status=status, body=content) finally: # Restore activity properties. activity.conversation.id = original_conversation_id activity.service_url = original_service_url activity.relates_to = original_relates_to + activity.recipient = original_recipient + + async def _post_content( + self, to_url: str, token: str, activity: Activity + ) -> (int, object): + headers_dict = { + "Content-type": "application/json; charset=utf-8", + } + if token: + headers_dict.update( + {"Authorization": f"Bearer {token}",} + ) + + json_content = json.dumps(activity.serialize()) + resp = await self._session.post( + to_url, data=json_content.encode("utf-8"), headers=headers_dict, + ) + resp.raise_for_status() + data = (await resp.read()).decode() + return resp.status, json.loads(data) if data else None async def post_buffered_activity( self,
diff --git a/libraries/botbuilder-integration-aiohttp/tests/test_bot_framework_http_client.py b/libraries/botbuilder-integration-aiohttp/tests/test_bot_framework_http_client.py --- a/libraries/botbuilder-integration-aiohttp/tests/test_bot_framework_http_client.py +++ b/libraries/botbuilder-integration-aiohttp/tests/test_bot_framework_http_client.py @@ -1,8 +1,71 @@ +from unittest.mock import Mock + import aiounittest +from botbuilder.schema import ConversationAccount, ChannelAccount from botbuilder.integration.aiohttp import BotFrameworkHttpClient +from botframework.connector.auth import CredentialProvider, Activity class TestBotFrameworkHttpClient(aiounittest.AsyncTestCase): async def test_should_create_connector_client(self): with self.assertRaises(TypeError): BotFrameworkHttpClient(None) + + async def test_adds_recipient_and_sets_it_back_to_null(self): + mock_credential_provider = Mock(spec=CredentialProvider) + + # pylint: disable=unused-argument + async def _mock_post_content( + to_url: str, token: str, activity: Activity + ) -> (int, object): + nonlocal self + self.assertIsNotNone(activity.recipient) + return 200, None + + client = BotFrameworkHttpClient(credential_provider=mock_credential_provider) + client._post_content = _mock_post_content # pylint: disable=protected-access + + activity = Activity(conversation=ConversationAccount()) + + await client.post_activity( + None, + None, + "https://skillbot.com/api/messages", + "https://parentbot.com/api/messages", + "NewConversationId", + activity, + ) + + assert activity.recipient is None + + async def test_does_not_overwrite_non_null_recipient_values(self): + skill_recipient_id = "skillBot" + mock_credential_provider = Mock(spec=CredentialProvider) + + # pylint: disable=unused-argument + async def _mock_post_content( + to_url: str, token: str, activity: Activity + ) -> (int, object): + nonlocal self + self.assertIsNotNone(activity.recipient) + self.assertEqual(skill_recipient_id, activity.recipient.id) + return 200, None + + client = BotFrameworkHttpClient(credential_provider=mock_credential_provider) + client._post_content = _mock_post_content # pylint: disable=protected-access + + activity = Activity( + conversation=ConversationAccount(), + recipient=ChannelAccount(id=skill_recipient_id), + ) + + await client.post_activity( + None, + None, + "https://skillbot.com/api/messages", + "https://parentbot.com/api/messages", + "NewConversationId", + activity, + ) + + assert activity.recipient.id == skill_recipient_id
Skill consumers should not be able to send Activities to skills without a recipient (Python) See [parent](https://github.com/microsoft/botframework-sdk/issues/5785). Issue may be specific to dotnet, need to verify if this is the case.
2020-04-21T21:36:49
microsoft/botbuilder-python
997
microsoft__botbuilder-python-997
[ "897" ]
3d32eaa4ad4e0118453ee083dc37a18c74aa3977
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/oauth_prompt.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/oauth_prompt.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/oauth_prompt.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/oauth_prompt.py @@ -124,7 +124,7 @@ async def begin_dialog( """ if dialog_context is None: raise TypeError( - f"OAuthPrompt.begin_dialog: Expected DialogContext but got NoneType instead" + f"OAuthPrompt.begin_dialog(): Expected DialogContext but got NoneType instead" ) options = options or PromptOptions() @@ -149,7 +149,7 @@ async def begin_dialog( if not isinstance(dialog_context.context.adapter, UserTokenProvider): raise TypeError( - "OAuthPrompt.get_user_token(): not supported by the current adapter" + "OAuthPrompt.begin_dialog(): not supported by the current adapter" ) output = await dialog_context.context.adapter.get_user_token( @@ -357,7 +357,7 @@ async def _send_oauth_card( ): if not hasattr(context.adapter, "get_oauth_sign_in_link"): raise Exception( - "OAuthPrompt.send_oauth_card(): get_oauth_sign_in_link() not supported by the current adapter" + "OAuthPrompt._send_oauth_card(): get_oauth_sign_in_link() not supported by the current adapter" ) link = await context.adapter.get_oauth_sign_in_link( @@ -450,12 +450,12 @@ async def _recognize_token(self, context: TurnContext) -> PromptRecognizerResult self._get_token_exchange_invoke_response( int(HTTPStatus.BAD_GATEWAY), "The bot's BotAdapter does not support token exchange operations." - " Ensure the bot's Adapter supports the ITokenExchangeProvider interface.", + " Ensure the bot's Adapter supports the ExtendedUserTokenProvider interface.", ) ) raise AttributeError( - "OAuthPrompt.recognize(): not supported by the current adapter." + "OAuthPrompt._recognize_token(): not supported by the current adapter." ) else: # No errors. Proceed with token exchange.
[PORT] Fix the interface name in the error message. > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3633 Interface looks like it changed name but the name in the error message didn't. # Changed projects * Microsoft.Bot.Builder.Dialogs
2020-04-24T19:22:01
microsoft/botbuilder-python
1,029
microsoft__botbuilder-python-1029
[ "1025" ]
ec9f9d1ea935ae516996c8e5ef3f3c95f75dfac3
diff --git a/libraries/botbuilder-ai/botbuilder/ai/qna/dialogs/qnamaker_dialog.py b/libraries/botbuilder-ai/botbuilder/ai/qna/dialogs/qnamaker_dialog.py --- a/libraries/botbuilder-ai/botbuilder/ai/qna/dialogs/qnamaker_dialog.py +++ b/libraries/botbuilder-ai/botbuilder/ai/qna/dialogs/qnamaker_dialog.py @@ -292,13 +292,12 @@ async def __call_generate_answer(self, step_context: WaterfallStepContext): # Check if active learning is enabled and send card # maximum_score_for_low_score_variation is the score above which no need to check for feedback. if ( - is_active_learning_enabled - and response.answers + response.answers and response.answers[0].score <= self.maximum_score_for_low_score_variation ): # Get filtered list of the response that support low score variation criteria. response.answers = qna_client.get_low_score_variation(response.answers) - if len(response.answers) > 1: + if len(response.answers) > 1 and is_active_learning_enabled: suggested_questions = [qna.questions[0] for qna in response.answers] message = QnACardBuilder.get_suggestions_card( suggested_questions,
diff --git a/libraries/botbuilder-ai/tests/qna/test_data/QnaMaker_TopNAnswer.json b/libraries/botbuilder-ai/tests/qna/test_data/QnaMaker_TopNAnswer.json new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-ai/tests/qna/test_data/QnaMaker_TopNAnswer.json @@ -0,0 +1,65 @@ +{ + "activeLearningEnabled": true, + "answers": [ + { + "questions": [ + "Q1" + ], + "answer": "A1", + "score": 80, + "id": 15, + "source": "Editorial", + "metadata": [ + { + "name": "topic", + "value": "value" + } + ] + }, + { + "questions": [ + "Q2" + ], + "answer": "A2", + "score": 78, + "id": 16, + "source": "Editorial", + "metadata": [ + { + "name": "topic", + "value": "value" + } + ] + }, + { + "questions": [ + "Q3" + ], + "answer": "A3", + "score": 75, + "id": 17, + "source": "Editorial", + "metadata": [ + { + "name": "topic", + "value": "value" + } + ] + }, + { + "questions": [ + "Q4" + ], + "answer": "A4", + "score": 50, + "id": 18, + "source": "Editorial", + "metadata": [ + { + "name": "topic", + "value": "value" + } + ] + } + ] +} \ No newline at end of file diff --git a/libraries/botbuilder-ai/tests/qna/test_data/QnaMaker_TopNAnswer_DisableActiveLearning.json b/libraries/botbuilder-ai/tests/qna/test_data/QnaMaker_TopNAnswer_DisableActiveLearning.json new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-ai/tests/qna/test_data/QnaMaker_TopNAnswer_DisableActiveLearning.json @@ -0,0 +1,65 @@ +{ + "activeLearningEnabled": false, + "answers": [ + { + "questions": [ + "Q1" + ], + "answer": "A1", + "score": 80, + "id": 15, + "source": "Editorial", + "metadata": [ + { + "name": "topic", + "value": "value" + } + ] + }, + { + "questions": [ + "Q2" + ], + "answer": "A2", + "score": 78, + "id": 16, + "source": "Editorial", + "metadata": [ + { + "name": "topic", + "value": "value" + } + ] + }, + { + "questions": [ + "Q3" + ], + "answer": "A3", + "score": 75, + "id": 17, + "source": "Editorial", + "metadata": [ + { + "name": "topic", + "value": "value" + } + ] + }, + { + "questions": [ + "Q4" + ], + "answer": "A4", + "score": 50, + "id": 18, + "source": "Editorial", + "metadata": [ + { + "name": "topic", + "value": "value" + } + ] + } + ] +} \ No newline at end of file diff --git a/libraries/botbuilder-ai/tests/qna/test_qna.py b/libraries/botbuilder-ai/tests/qna/test_qna.py --- a/libraries/botbuilder-ai/tests/qna/test_qna.py +++ b/libraries/botbuilder-ai/tests/qna/test_qna.py @@ -2,6 +2,7 @@ # Licensed under the MIT License. # pylint: disable=protected-access +# pylint: disable=too-many-lines import json from os import path @@ -811,6 +812,46 @@ async def test_should_answer_with_low_score_without_provided_context(self): ) self.assertEqual(True, results[0].score < 1, "Score should be low.") + async def test_low_score_variation(self): + qna = QnAMaker(QnaApplicationTest.tests_endpoint) + options = QnAMakerOptions(top=5, context=None) + + turn_context = QnaApplicationTest._get_context("Q11", TestAdapter()) + response_json = QnaApplicationTest._get_json_for_file( + "QnaMaker_TopNAnswer.json" + ) + + # active learning enabled + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(turn_context, options) + self.assertIsNotNone(results) + self.assertEqual(4, len(results), "should get four results") + + filtered_results = qna.get_low_score_variation(results) + self.assertIsNotNone(filtered_results) + self.assertEqual(3, len(filtered_results), "should get three results") + + # active learning disabled + turn_context = QnaApplicationTest._get_context("Q11", TestAdapter()) + response_json = QnaApplicationTest._get_json_for_file( + "QnaMaker_TopNAnswer_DisableActiveLearning.json" + ) + + with patch( + "aiohttp.ClientSession.post", + return_value=aiounittest.futurized(response_json), + ): + results = await qna.get_answers(turn_context, options) + self.assertIsNotNone(results) + self.assertEqual(4, len(results), "should get four results") + + filtered_results = qna.get_low_score_variation(results) + self.assertIsNotNone(filtered_results) + self.assertEqual(3, len(filtered_results), "should get three results") + @classmethod async def _get_service_result( cls,
[PORT] [QnAMaker] Volitile LowScoreVariation and Active Learning Issue fix > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3786 For issue #3714 # Changed projects * Microsoft.Bot.Builder.AI.QnA * Microsoft.Bot.Builder.AI.QnA.Tests [changes required]
2020-04-29T21:45:46
microsoft/botbuilder-python
1,067
microsoft__botbuilder-python-1067
[ "1065" ]
3a242b11d536c6fa86c2bb4f8d98a31094ef19b4
diff --git a/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py b/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py --- a/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py +++ b/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py @@ -350,7 +350,11 @@ async def on_teams_members_added_dispatch( # pylint: disable=unused-argument team_members_added = [] for member in members_added: - if member.additional_properties != {}: + is_bot = ( + turn_context.activity.recipient is not None + and member.id == turn_context.activity.recipient.id + ) + if member.additional_properties != {} or is_bot: team_members_added.append( deserializer_helper(TeamsChannelAccount, member) )
diff --git a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py --- a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py +++ b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py @@ -385,6 +385,38 @@ async def test_on_teams_members_added_activity(self): assert bot.record[0] == "on_conversation_update_activity" assert bot.record[1] == "on_teams_members_added" + async def test_bot_on_teams_members_added_activity(self): + # arrange + activity = Activity( + recipient=ChannelAccount(id="botid"), + type=ActivityTypes.conversation_update, + channel_data={ + "eventType": "teamMemberAdded", + "team": {"id": "team_id_1", "name": "new_team_name"}, + }, + members_added=[ + ChannelAccount( + id="botid", + name="test_user", + aad_object_id="asdfqwerty", + role="tester", + ) + ], + channel_id=Channels.ms_teams, + conversation=ConversationAccount(id="456"), + ) + + turn_context = TurnContext(SimpleAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_members_added" + async def test_on_teams_members_removed_activity(self): # arrange activity = Activity(
onTeamsMembersAddedEvent handler doesn't run when bot is the member When a bot receives an onTeamsMemberAdded event where the member added was the bot, a 502 error is thrown, which results in this event never being fired. Cause: The event calls the getMember API, which is the source of the 502. This API cannot be passed a bot ID. Fix: Check to see if the member added is the bot, and if it is return a truncated TeamsChannelAccount.
2020-05-14T19:02:41
microsoft/botbuilder-python
1,145
microsoft__botbuilder-python-1145
[ "1134" ]
0e96543724c4066e1a0ae9193ee8df70d0d03064
diff --git a/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py b/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py --- a/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py +++ b/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py @@ -1508,17 +1508,21 @@ class TeamInfo(Model): :type id: str :param name: Name of team. :type name: str + :param name: Azure AD Teams group ID. + :type name: str """ _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, + "aad_group_id": {"key": "aadGroupId", "type": "str"}, } def __init__(self, **kwargs): super(TeamInfo, self).__init__(**kwargs) self.id = kwargs.get("id", None) self.name = kwargs.get("name", None) + self.aad_group_id = kwargs.get("aad_group_id", None) class TeamsChannelAccount(ChannelAccount): diff --git a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py --- a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py +++ b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py @@ -1773,17 +1773,23 @@ class TeamInfo(Model): :type id: str :param name: Name of team. :type name: str + :param name: Azure AD Teams group ID. + :type name: str """ _attribute_map = { "id": {"key": "id", "type": "str"}, "name": {"key": "name", "type": "str"}, + "aad_group_id": {"key": "aadGroupId", "type": "str"}, } - def __init__(self, *, id: str = None, name: str = None, **kwargs) -> None: + def __init__( + self, *, id: str = None, name: str = None, aad_group_id: str = None, **kwargs + ) -> None: super(TeamInfo, self).__init__(**kwargs) self.id = id self.name = name + self.aad_group_id = aad_group_id class TeamsChannelAccount(ChannelAccount):
diff --git a/libraries/botbuilder-core/tests/teams/test_teams_channel_data.py b/libraries/botbuilder-core/tests/teams/test_teams_channel_data.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-core/tests/teams/test_teams_channel_data.py @@ -0,0 +1,30 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import aiounittest + +from botbuilder.schema import Activity +from botbuilder.schema.teams import TeamsChannelData +from botbuilder.core.teams import teams_get_team_info + + +class TestTeamsChannelData(aiounittest.AsyncTestCase): + def test_teams_aad_group_id_deserialize(self): + # Arrange + raw_channel_data = {"team": {"aadGroupId": "teamGroup123"}} + + # Act + channel_data = TeamsChannelData().deserialize(raw_channel_data) + + # Assert + assert channel_data.team.aad_group_id == "teamGroup123" + + def test_teams_get_team_info(self): + # Arrange + activity = Activity(channel_data={"team": {"aadGroupId": "teamGroup123"}}) + + # Act + team_info = teams_get_team_info(activity) + + # Assert + assert team_info.aad_group_id == "teamGroup123"
TeamInfo type does not expose aadGroupId (python) See [parent](https://github.com/microsoft/botframework-sdk/issues/5870)
2020-06-17T19:06:04
microsoft/botbuilder-python
1,167
microsoft__botbuilder-python-1167
[ "1156" ]
922a6224a4162fbd0962440d04967b3068d8648a
diff --git a/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py b/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py --- a/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py +++ b/libraries/botbuilder-schema/botbuilder/schema/teams/_models.py @@ -459,6 +459,8 @@ class MessageActionsPayload(Model): :type importance: str or ~botframework.connector.teams.models.enum :param locale: Locale of the message set by the client. :type locale: str + :param link_to_message: Link back to the message. + :type link_to_message: str :param from_property: Sender of the message. :type from_property: ~botframework.connector.teams.models.MessageActionsPayloadFrom @@ -489,6 +491,7 @@ class MessageActionsPayload(Model): "summary": {"key": "summary", "type": "str"}, "importance": {"key": "importance", "type": "str"}, "locale": {"key": "locale", "type": "str"}, + "link_to_message": {"key": "linkToMessage", "type": "str"}, "from_property": {"key": "from", "type": "MessageActionsPayloadFrom"}, "body": {"key": "body", "type": "MessageActionsPayloadBody"}, "attachment_layout": {"key": "attachmentLayout", "type": "str"}, @@ -512,6 +515,7 @@ def __init__(self, **kwargs): self.summary = kwargs.get("summary", None) self.importance = kwargs.get("importance", None) self.locale = kwargs.get("locale", None) + self.link_to_message = kwargs.get("link_to_message", None) self.from_property = kwargs.get("from_property", None) self.body = kwargs.get("body", None) self.attachment_layout = kwargs.get("attachment_layout", None) diff --git a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py --- a/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py +++ b/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py @@ -550,6 +550,8 @@ class MessageActionsPayload(Model): :type importance: str :param locale: Locale of the message set by the client. :type locale: str + :param link_to_message: Link back to the message. + :type link_to_message: str :param from_property: Sender of the message. :type from_property: ~botframework.connector.teams.models.MessageActionsPayloadFrom @@ -580,6 +582,7 @@ class MessageActionsPayload(Model): "summary": {"key": "summary", "type": "str"}, "importance": {"key": "importance", "type": "str"}, "locale": {"key": "locale", "type": "str"}, + "link_to_message": {"key": "linkToMessage", "type": "str"}, "from_property": {"key": "from", "type": "MessageActionsPayloadFrom"}, "body": {"key": "body", "type": "MessageActionsPayloadBody"}, "attachment_layout": {"key": "attachmentLayout", "type": "str"}, @@ -604,6 +607,7 @@ def __init__( summary: str = None, importance=None, locale: str = None, + link_to_message: str = None, from_property=None, body=None, attachment_layout: str = None, @@ -623,6 +627,7 @@ def __init__( self.summary = summary self.importance = importance self.locale = locale + self.link_to_message = link_to_message self.from_property = from_property self.body = body self.attachment_layout = attachment_layout
diff --git a/libraries/botbuilder-schema/tests/teams/test_message_actions_payload.py b/libraries/botbuilder-schema/tests/teams/test_message_actions_payload.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-schema/tests/teams/test_message_actions_payload.py @@ -0,0 +1,146 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import aiounittest +from botframework.connector.models import ( + MessageActionsPayloadFrom, + MessageActionsPayloadBody, + MessageActionsPayloadAttachment, + MessageActionsPayloadMention, + MessageActionsPayloadReaction, +) +from botbuilder.schema.teams import MessageActionsPayload + + +class TestingMessageActionsPayload(aiounittest.AsyncTestCase): + # Arrange + test_id = "01" + reply_to_id = "test_reply_to_id" + message_type = "test_message_type" + created_date_time = "01/01/2000" + last_modified_date_time = "01/01/2000" + deleted = False + subject = "test_subject" + summary = "test_summary" + importance = "high" + locale = "test_locale" + link_to_message = "https://teams.microsoft/com/l/message/testing-id" + from_property = MessageActionsPayloadFrom() + body = MessageActionsPayloadBody + attachment_layout = "test_attachment_layout" + attachments = [MessageActionsPayloadAttachment()] + mentions = [MessageActionsPayloadMention()] + reactions = [MessageActionsPayloadReaction()] + + # Act + message = MessageActionsPayload( + id=test_id, + reply_to_id=reply_to_id, + message_type=message_type, + created_date_time=created_date_time, + last_modified_date_time=last_modified_date_time, + deleted=deleted, + subject=subject, + summary=summary, + importance=importance, + locale=locale, + link_to_message=link_to_message, + from_property=from_property, + body=body, + attachment_layout=attachment_layout, + attachments=attachments, + mentions=mentions, + reactions=reactions, + ) + + def test_assign_id(self, message_action_payload=message, test_id=test_id): + # Assert + self.assertEqual(message_action_payload.id, test_id) + + def test_assign_reply_to_id( + self, message_action_payload=message, reply_to_id=reply_to_id + ): + # Assert + self.assertEqual(message_action_payload.reply_to_id, reply_to_id) + + def test_assign_message_type( + self, message_action_payload=message, message_type=message_type + ): + # Assert + self.assertEqual(message_action_payload.message_type, message_type) + + def test_assign_created_date_time( + self, message_action_payload=message, created_date_time=created_date_time + ): + # Assert + self.assertEqual(message_action_payload.created_date_time, created_date_time) + + def test_assign_last_modified_date_time( + self, + message_action_payload=message, + last_modified_date_time=last_modified_date_time, + ): + # Assert + self.assertEqual( + message_action_payload.last_modified_date_time, last_modified_date_time + ) + + def test_assign_deleted(self, message_action_payload=message, deleted=deleted): + # Assert + self.assertEqual(message_action_payload.deleted, deleted) + + def test_assign_subject(self, message_action_payload=message, subject=subject): + # Assert + self.assertEqual(message_action_payload.subject, subject) + + def test_assign_summary(self, message_action_payload=message, summary=summary): + # Assert + self.assertEqual(message_action_payload.summary, summary) + + def test_assign_importance( + self, message_action_payload=message, importance=importance + ): + # Assert + self.assertEqual(message_action_payload.importance, importance) + + def test_assign_locale(self, message_action_payload=message, locale=locale): + # Assert + self.assertEqual(message_action_payload.locale, locale) + + def test_assign_link_to_message( + self, message_action_payload=message, link_to_message=link_to_message + ): + # Assert + self.assertEqual(message_action_payload.link_to_message, link_to_message) + + def test_assign_from_property( + self, message_action_payload=message, from_property=from_property + ): + # Assert + self.assertEqual(message_action_payload.from_property, from_property) + + def test_assign_body(self, message_action_payload=message, body=body): + # Assert + self.assertEqual(message_action_payload.body, body) + + def test_assign_attachment_layout( + self, message_action_payload=message, attachment_layout=attachment_layout + ): + # Assert + self.assertEqual(message_action_payload.attachment_layout, attachment_layout) + + def test_assign_attachments( + self, message_action_payload=message, attachments=attachments + ): + # Assert + self.assertEqual(message_action_payload.attachments, attachments) + + def test_assign_mentions(self, message_action_payload=message, mentions=mentions): + # Assert + self.assertEqual(message_action_payload.mentions, mentions) + + def test_assign_reactions( + self, message_action_payload=message, reactions=reactions + ): + # Assert + self.assertEqual(message_action_payload.reactions, reactions)
Add linkToMessage to the MessageActionsPayload object (Python) See [parent](https://github.com/microsoft/botframework-sdk/issues/5894)
2020-06-22T21:19:06
microsoft/botbuilder-python
1,182
microsoft__botbuilder-python-1182
[ "1157" ]
c3124920206776652dca0a0d83eccdfbd2439ce4
diff --git a/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py b/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py --- a/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py +++ b/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py @@ -8,12 +8,109 @@ # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- -from datetime import datetime +from botbuilder.schema._connector_client_enums import ActivityTypes +from datetime import datetime from msrest.serialization import Model from msrest.exceptions import HttpOperationError +class ConversationReference(Model): + """An object relating to a particular point in a conversation. + + :param activity_id: (Optional) ID of the activity to refer to + :type activity_id: str + :param user: (Optional) User participating in this conversation + :type user: ~botframework.connector.models.ChannelAccount + :param bot: Bot participating in this conversation + :type bot: ~botframework.connector.models.ChannelAccount + :param conversation: Conversation reference + :type conversation: ~botframework.connector.models.ConversationAccount + :param channel_id: Channel ID + :type channel_id: str + :param locale: A locale name for the contents of the text field. + The locale name is a combination of an ISO 639 two- or three-letter + culture code associated with a language and an ISO 3166 two-letter + subculture code associated with a country or region. + The locale name can also correspond to a valid BCP-47 language tag. + :type locale: str + :param service_url: Service endpoint where operations concerning the + referenced conversation may be performed + :type service_url: str + """ + + _attribute_map = { + "activity_id": {"key": "activityId", "type": "str"}, + "user": {"key": "user", "type": "ChannelAccount"}, + "bot": {"key": "bot", "type": "ChannelAccount"}, + "conversation": {"key": "conversation", "type": "ConversationAccount"}, + "channel_id": {"key": "channelId", "type": "str"}, + "locale": {"key": "locale", "type": "str"}, + "service_url": {"key": "serviceUrl", "type": "str"}, + } + + def __init__( + self, + *, + activity_id: str = None, + user=None, + bot=None, + conversation=None, + channel_id: str = None, + locale: str = None, + service_url: str = None, + **kwargs + ) -> None: + super(ConversationReference, self).__init__(**kwargs) + self.activity_id = activity_id + self.user = user + self.bot = bot + self.conversation = conversation + self.channel_id = channel_id + self.locale = locale + self.service_url = service_url + + +class Mention(Model): + """Mention information (entity type: "mention"). + + :param mentioned: The mentioned user + :type mentioned: ~botframework.connector.models.ChannelAccount + :param text: Sub Text which represents the mention (can be null or empty) + :type text: str + :param type: Type of this entity (RFC 3987 IRI) + :type type: str + """ + + _attribute_map = { + "mentioned": {"key": "mentioned", "type": "ChannelAccount"}, + "text": {"key": "text", "type": "str"}, + "type": {"key": "type", "type": "str"}, + } + + def __init__( + self, *, mentioned=None, text: str = None, type: str = None, **kwargs + ) -> None: + super(Mention, self).__init__(**kwargs) + self.mentioned = mentioned + self.text = text + self.type = type + + +class ResourceResponse(Model): + """A response containing a resource ID. + + :param id: Id of the resource + :type id: str + """ + + _attribute_map = {"id": {"key": "id", "type": "str"}} + + def __init__(self, *, id: str = None, **kwargs) -> None: + super(ResourceResponse, self).__init__(**kwargs) + self.id = id + + class Activity(Model): """An Activity is the basic communication type for the Bot Framework 3.0 protocol. @@ -288,9 +385,251 @@ def __init__( self.semantic_action = semantic_action self.caller_id = caller_id + def apply_conversation_reference( + self, reference: ConversationReference, is_incoming: bool = False + ): + """ + Updates this activity with the delivery information from an existing ConversationReference + + :param reference: The existing conversation reference. + :param is_incoming: Optional, True to treat the activity as an + incoming activity, where the bot is the recipient; otherwise, False. + Default is False, and the activity will show the bot as the sender. + + :returns: his activity, updated with the delivery information. + + .. remarks:: + Call GetConversationReference on an incoming + activity to get a conversation reference that you can then use to update an + outgoing activity with the correct delivery information. + """ + self.channel_id = reference.channel_id + self.service_url = reference.service_url + self.conversation = reference.conversation + + if reference.locale is not None: + self.locale = reference.locale + + if is_incoming: + self.from_property = reference.user + self.recipient = reference.bot + + if reference.activity_id is not None: + self.id = reference.activity_id + else: + self.from_property = reference.bot + self.recipient = reference.user + + if reference.activity_id is not None: + self.reply_to_id = reference.activity_id + + return self + + def as_contact_relation_update_activity(self): + """ + Returns this activity as a ContactRelationUpdateActivity object; + or None, if this is not that type of activity. + + :returns: This activity as a message activity; or None. + """ + return ( + self if self.__is_activity(ActivityTypes.contact_relation_update) else None + ) + + def as_conversation_update_activity(self): + """ + Returns this activity as a ConversationUpdateActivity object; + or None, if this is not that type of activity. + + :returns: This activity as a conversation update activity; or None. + """ + return self if self.__is_activity(ActivityTypes.conversation_update) else None + + def as_end_of_conversation_activity(self): + """ + Returns this activity as an EndOfConversationActivity object; + or None, if this is not that type of activity. + + :returns: This activity as an end of conversation activity; or None. + """ + return self if self.__is_activity(ActivityTypes.end_of_conversation) else None + + def as_event_activity(self): + """ + Returns this activity as an EventActivity object; + or None, if this is not that type of activity. + + :returns: This activity as an event activity; or None. + """ + return self if self.__is_activity(ActivityTypes.event) else None + + def as_handoff_activity(self): + """ + Returns this activity as a HandoffActivity object; + or None, if this is not that type of activity. + + :returns: This activity as a handoff activity; or None. + """ + return self if self.__is_activity(ActivityTypes.handoff) else None + + def as_installation_update_activity(self): + """ + Returns this activity as an InstallationUpdateActivity object; + or None, if this is not that type of activity. + + :returns: This activity as an installation update activity; or None. + """ + return self if self.__is_activity(ActivityTypes.installation_update) else None + + def as_invoke_activity(self): + """ + Returns this activity as an InvokeActivity object; + or None, if this is not that type of activity. + + :returns: This activity as an invoke activity; or None. + """ + return self if self.__is_activity(ActivityTypes.invoke) else None + + def as_message_activity(self): + """ + Returns this activity as a MessageActivity object; + or None, if this is not that type of activity. + + :returns: This activity as a message activity; or None. + """ + return self if self.__is_activity(ActivityTypes.message) else None + + def as_message_delete_activity(self): + """ + Returns this activity as a MessageDeleteActivity object; + or None, if this is not that type of activity. + + :returns: This activity as a message delete request; or None. + """ + return self if self.__is_activity(ActivityTypes.message_delete) else None + + def as_message_reaction_activity(self): + """ + Returns this activity as a MessageReactionActivity object; + or None, if this is not that type of activity. + + :return: This activity as a message reaction activity; or None. + """ + return self if self.__is_activity(ActivityTypes.message_reaction) else None + + def as_message_update_activity(self): + """ + Returns this activity as an MessageUpdateActivity object; + or None, if this is not that type of activity. + + :returns: This activity as a message update request; or None. + """ + return self if self.__is_activity(ActivityTypes.message_update) else None + + def as_suggestion_activity(self): + """ + Returns this activity as a SuggestionActivity object; + or None, if this is not that type of activity. + + :returns: This activity as a suggestion activity; or None. + """ + return self if self.__is_activity(ActivityTypes.suggestion) else None + + def as_trace_activity(self): + """ + Returns this activity as a TraceActivity object; + or None, if this is not that type of activity. + + :returns: This activity as a trace activity; or None. + """ + return self if self.__is_activity(ActivityTypes.trace) else None + + def as_typing_activity(self): + """ + Returns this activity as a TypingActivity object; + or null, if this is not that type of activity. + + :returns: This activity as a typing activity; or null. + """ + return self if self.__is_activity(ActivityTypes.typing) else None + + @staticmethod + def create_contact_relation_update_activity(): + """ + Creates an instance of the :class:`Activity` class as aContactRelationUpdateActivity object. + + :returns: The new contact relation update activity. + """ + return Activity(type=ActivityTypes.contact_relation_update) + + @staticmethod + def create_conversation_update_activity(): + """ + Creates an instance of the :class:`Activity` class as a ConversationUpdateActivity object. + + :returns: The new conversation update activity. + """ + return Activity(type=ActivityTypes.conversation_update) + + @staticmethod + def create_end_of_conversation_activity(): + """ + Creates an instance of the :class:`Activity` class as an EndOfConversationActivity object. + + :returns: The new end of conversation activity. + """ + return Activity(type=ActivityTypes.end_of_conversation) + + @staticmethod + def create_event_activity(): + """ + Creates an instance of the :class:`Activity` class as an EventActivity object. + + :returns: The new event activity. + """ + return Activity(type=ActivityTypes.event) + + @staticmethod + def create_handoff_activity(): + """ + Creates an instance of the :class:`Activity` class as a HandoffActivity object. + + :returns: The new handoff activity. + """ + return Activity(type=ActivityTypes.handoff) + + @staticmethod + def create_invoke_activity(): + """ + Creates an instance of the :class:`Activity` class as an InvokeActivity object. + + :returns: The new invoke activity. + """ + return Activity(type=ActivityTypes.invoke) + + @staticmethod + def create_message_activity(): + """ + Creates an instance of the :class:`Activity` class as a MessageActivity object. + + :returns: The new message activity. + """ + return Activity(type=ActivityTypes.message) + def create_reply(self, text: str = None, locale: str = None): + """ + Creates a new message activity as a response to this activity. + + :param text: The text of the reply. + :param locale: The language code for the text. + + :returns: The new message activity. + + .. remarks:: + The new activity sets up routing information based on this activity. + """ return Activity( - type="message", + type=ActivityTypes.message, timestamp=datetime.utcnow(), from_property=ChannelAccount( id=self.recipient.id if self.recipient else None, @@ -314,6 +653,192 @@ def create_reply(self, text: str = None, locale: str = None): entities=[], ) + def create_trace( + self, name: str, value: object = None, value_type: str = None, label: str = None + ): + """ + Creates a new trace activity based on this activity. + + :param name: The name of the trace operation to create. + :param value: Optional, the content for this trace operation. + :param value_type: Optional, identifier for the format of the value + Default is the name of type of the value. + :param label: Optional, a descriptive label for this trace operation. + + :returns: The new trace activity. + """ + if not value_type and value: + value_type = type(value) + + return Activity( + type=ActivityTypes.trace, + timestamp=datetime.utcnow(), + from_property=ChannelAccount( + id=self.recipient.id if self.recipient else None, + name=self.recipient.name if self.recipient else None, + ), + recipient=ChannelAccount( + id=self.from_property.id if self.from_property else None, + name=self.from_property.name if self.from_property else None, + ), + reply_to_id=self.id, + service_url=self.service_url, + channel_id=self.channel_id, + conversation=ConversationAccount( + is_group=self.conversation.is_group, + id=self.conversation.id, + name=self.conversation.name, + ), + name=name, + label=label, + value_type=value_type, + value=value, + ).as_trace_activity() + + @staticmethod + def create_trace_activity( + name: str, value: object = None, value_type: str = None, label: str = None + ): + """ + Creates an instance of the :class:`Activity` class as a TraceActivity object. + + :param name: The name of the trace operation to create. + :param value: Optional, the content for this trace operation. + :param value_type: Optional, identifier for the format of the value. + Default is the name of type of the value. + :param label: Optional, a descriptive label for this trace operation. + + :returns: The new trace activity. + """ + if not value_type and value: + value_type = type(value) + + return Activity( + type=ActivityTypes.trace, + name=name, + label=label, + value_type=value_type, + value=value, + ) + + @staticmethod + def create_typing_activity(): + """ + Creates an instance of the :class:`Activity` class as a TypingActivity object. + + :returns: The new typing activity. + """ + return Activity(type=ActivityTypes.typing) + + def get_conversation_reference(self): + """ + Creates a ConversationReference based on this activity. + + :returns: A conversation reference for the conversation that contains this activity. + """ + return ConversationReference( + activity_id=self.id, + user=self.from_property, + bot=self.recipient, + conversation=self.conversation, + channel_id=self.channel_id, + locale=self.locale, + service_url=self.service_url, + ) + + def get_mentions(self) -> [Mention]: + """ + Resolves the mentions from the entities of this activity. + + :returns: The array of mentions; or an empty array, if none are found. + + .. remarks:: + This method is defined on the :class:`Activity` class, but is only intended + for use with a message activity, where the activity Activity.Type is set to + ActivityTypes.Message. + """ + _list = self.entities + return [x for x in _list if str(x.type).lower() == "mention"] + + def get_reply_conversation_reference( + self, reply: ResourceResponse + ) -> ConversationReference: + """ + Create a ConversationReference based on this Activity's Conversation info + and the ResourceResponse from sending an activity. + + :param reply: ResourceResponse returned from send_activity. + + :return: A ConversationReference that can be stored and used later to delete or update the activity. + """ + reference = self.get_conversation_reference() + reference.activity_id = reply.id + return reference + + def has_content(self) -> bool: + """ + Indicates whether this activity has content. + + :returns: True, if this activity has any content to send; otherwise, false. + + .. remarks:: + This method is defined on the :class:`Activity` class, but is only intended + for use with a message activity, where the activity Activity.Type is set to + ActivityTypes.Message. + """ + if self.text and self.text.strip(): + return True + + if self.summary and self.summary.strip(): + return True + + if self.attachments and len(self.attachments) > 0: + return True + + if self.channel_data: + return True + + return False + + def is_from_streaming_connection(self) -> bool: + """ + Determine if the Activity was sent via an Http/Https connection or Streaming + This can be determined by looking at the service_url property: + (1) All channels that send messages via http/https are not streaming + (2) Channels that send messages via streaming have a ServiceUrl that does not begin with http/https. + + :returns: True if the Activity originated from a streaming connection. + """ + if self.service_url: + return not self.service_url.lower().startswith("http") + return False + + def __is_activity(self, activity_type: str) -> bool: + """ + Indicates whether this activity is of a specified activity type. + + :param activity_type: The activity type to check for. + :return: True if this activity is of the specified activity type; otherwise, False. + """ + if self.type is None: + return False + + type_attribute = str(self.type).lower() + activity_type = str(activity_type).lower() + + result = type_attribute.startswith(activity_type) + + if result: + result = len(type_attribute) == len(activity_type) + + if not result: + result = ( + len(type_attribute) > len(activity_type) + and type_attribute[len(activity_type)] == "/" + ) + + return result + class AnimationCard(Model): """An animation card (Ex: gif or short video clip). @@ -903,62 +1428,6 @@ def __init__( self.tenant_id = tenant_id -class ConversationReference(Model): - """An object relating to a particular point in a conversation. - - :param activity_id: (Optional) ID of the activity to refer to - :type activity_id: str - :param user: (Optional) User participating in this conversation - :type user: ~botframework.connector.models.ChannelAccount - :param bot: Bot participating in this conversation - :type bot: ~botframework.connector.models.ChannelAccount - :param conversation: Conversation reference - :type conversation: ~botframework.connector.models.ConversationAccount - :param channel_id: Channel ID - :type channel_id: str - :param locale: A locale name for the contents of the text field. - The locale name is a combination of an ISO 639 two- or three-letter - culture code associated with a language and an ISO 3166 two-letter - subculture code associated with a country or region. - The locale name can also correspond to a valid BCP-47 language tag. - :type locale: str - :param service_url: Service endpoint where operations concerning the - referenced conversation may be performed - :type service_url: str - """ - - _attribute_map = { - "activity_id": {"key": "activityId", "type": "str"}, - "user": {"key": "user", "type": "ChannelAccount"}, - "bot": {"key": "bot", "type": "ChannelAccount"}, - "conversation": {"key": "conversation", "type": "ConversationAccount"}, - "channel_id": {"key": "channelId", "type": "str"}, - "locale": {"key": "locale", "type": "str"}, - "service_url": {"key": "serviceUrl", "type": "str"}, - } - - def __init__( - self, - *, - activity_id: str = None, - user=None, - bot=None, - conversation=None, - channel_id: str = None, - locale: str = None, - service_url: str = None, - **kwargs - ) -> None: - super(ConversationReference, self).__init__(**kwargs) - self.activity_id = activity_id - self.user = user - self.bot = bot - self.conversation = conversation - self.channel_id = channel_id - self.locale = locale - self.service_url = service_url - - class ConversationResourceResponse(Model): """A response containing a resource. @@ -1349,32 +1818,6 @@ def __init__(self, *, url: str = None, profile: str = None, **kwargs) -> None: self.profile = profile -class Mention(Model): - """Mention information (entity type: "mention"). - - :param mentioned: The mentioned user - :type mentioned: ~botframework.connector.models.ChannelAccount - :param text: Sub Text which represents the mention (can be null or empty) - :type text: str - :param type: Type of this entity (RFC 3987 IRI) - :type type: str - """ - - _attribute_map = { - "mentioned": {"key": "mentioned", "type": "ChannelAccount"}, - "text": {"key": "text", "type": "str"}, - "type": {"key": "type", "type": "str"}, - } - - def __init__( - self, *, mentioned=None, text: str = None, type: str = None, **kwargs - ) -> None: - super(Mention, self).__init__(**kwargs) - self.mentioned = mentioned - self.text = text - self.type = type - - class MessageReaction(Model): """Message reaction object. @@ -1600,20 +2043,6 @@ def __init__( self.tap = tap -class ResourceResponse(Model): - """A response containing a resource ID. - - :param id: Id of the resource - :type id: str - """ - - _attribute_map = {"id": {"key": "id", "type": "str"}} - - def __init__(self, *, id: str = None, **kwargs) -> None: - super(ResourceResponse, self).__init__(**kwargs) - self.id = id - - class SemanticAction(Model): """Represents a reference to a programmatic action.
diff --git a/libraries/botbuilder-schema/tests/test_activity.py b/libraries/botbuilder-schema/tests/test_activity.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-schema/tests/test_activity.py @@ -0,0 +1,745 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +import aiounittest +from botbuilder.schema import ( + Activity, + ConversationReference, + ConversationAccount, + ChannelAccount, + Entity, + ResourceResponse, + Attachment, +) +from botbuilder.schema._connector_client_enums import ActivityTypes + + +class TestActivity(aiounittest.AsyncTestCase): + def test_constructor(self): + # Arrange + activity = Activity() + + # Assert + self.assertIsNotNone(activity) + self.assertIsNone(activity.type) + self.assertIsNone(activity.id) + self.assertIsNone(activity.timestamp) + self.assertIsNone(activity.local_timestamp) + self.assertIsNone(activity.local_timezone) + self.assertIsNone(activity.service_url) + self.assertIsNone(activity.channel_id) + self.assertIsNone(activity.from_property) + self.assertIsNone(activity.conversation) + self.assertIsNone(activity.recipient) + self.assertIsNone(activity.text_format) + self.assertIsNone(activity.attachment_layout) + self.assertIsNone(activity.members_added) + self.assertIsNone(activity.members_removed) + self.assertIsNone(activity.reactions_added) + self.assertIsNone(activity.reactions_removed) + self.assertIsNone(activity.topic_name) + self.assertIsNone(activity.history_disclosed) + self.assertIsNone(activity.locale) + self.assertIsNone(activity.text) + self.assertIsNone(activity.speak) + self.assertIsNone(activity.input_hint) + self.assertIsNone(activity.summary) + self.assertIsNone(activity.suggested_actions) + self.assertIsNone(activity.attachments) + self.assertIsNone(activity.entities) + self.assertIsNone(activity.channel_data) + self.assertIsNone(activity.action) + self.assertIsNone(activity.reply_to_id) + self.assertIsNone(activity.label) + self.assertIsNone(activity.value_type) + self.assertIsNone(activity.value) + self.assertIsNone(activity.name) + self.assertIsNone(activity.relates_to) + self.assertIsNone(activity.code) + self.assertIsNone(activity.expiration) + self.assertIsNone(activity.importance) + self.assertIsNone(activity.delivery_mode) + self.assertIsNone(activity.listen_for) + self.assertIsNone(activity.text_highlights) + self.assertIsNone(activity.semantic_action) + self.assertIsNone(activity.caller_id) + + def test_apply_conversation_reference(self): + # Arrange + activity = self.__create_activity() + conversation_reference = ConversationReference( + channel_id="123", + service_url="serviceUrl", + conversation=ConversationAccount(id="456"), + user=ChannelAccount(id="abc"), + bot=ChannelAccount(id="def"), + activity_id="12345", + locale="en-uS", + ) + + # Act + activity.apply_conversation_reference(reference=conversation_reference) + + # Assert + self.assertEqual(conversation_reference.channel_id, activity.channel_id) + self.assertEqual(conversation_reference.locale, activity.locale) + self.assertEqual(conversation_reference.service_url, activity.service_url) + self.assertEqual( + conversation_reference.conversation.id, activity.conversation.id + ) + self.assertEqual(conversation_reference.bot.id, activity.from_property.id) + self.assertEqual(conversation_reference.user.id, activity.recipient.id) + self.assertEqual(conversation_reference.activity_id, activity.reply_to_id) + + def test_apply_conversation_reference_with_is_incoming_true(self): + # Arrange + activity = self.__create_activity() + conversation_reference = ConversationReference( + channel_id="cr_123", + service_url="cr_serviceUrl", + conversation=ConversationAccount(id="cr_456"), + user=ChannelAccount(id="cr_abc"), + bot=ChannelAccount(id="cr_def"), + activity_id="cr_12345", + locale="en-uS", + ) + + # Act + activity.apply_conversation_reference( + reference=conversation_reference, is_incoming=True + ) + + # Assert + self.assertEqual(conversation_reference.channel_id, activity.channel_id) + self.assertEqual(conversation_reference.locale, activity.locale) + self.assertEqual(conversation_reference.service_url, activity.service_url) + self.assertEqual( + conversation_reference.conversation.id, activity.conversation.id + ) + self.assertEqual(conversation_reference.user.id, activity.from_property.id) + self.assertEqual(conversation_reference.bot.id, activity.recipient.id) + self.assertEqual(conversation_reference.activity_id, activity.id) + + def test_as_contact_relation_update_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.contact_relation_update + + # Act + result = activity.as_contact_relation_update_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.contact_relation_update) + + def test_as_contact_relation_update_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_contact_relation_update_activity() + + # Assert + self.assertIsNone(result) + + def test_as_conversation_update_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.conversation_update + + # Act + result = activity.as_conversation_update_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.conversation_update) + + def test_as_conversation_update_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_conversation_update_activity() + + # Assert + self.assertIsNone(result) + + def test_as_end_of_conversation_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.end_of_conversation + + # Act + result = activity.as_end_of_conversation_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.end_of_conversation) + + def test_as_end_of_conversation_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_end_of_conversation_activity() + + # Assert + self.assertIsNone(result) + + def test_as_event_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.event + + # Act + result = activity.as_event_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.event) + + def test_as_event_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_event_activity() + + # Assert + self.assertIsNone(result) + + def test_as_handoff_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.handoff + + # Act + result = activity.as_handoff_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.handoff) + + def test_as_handoff_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_handoff_activity() + + # Assert + self.assertIsNone(result) + + def test_as_installation_update_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.installation_update + + # Act + result = activity.as_installation_update_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.installation_update) + + def test_as_installation_update_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_installation_update_activity() + + # Assert + self.assertIsNone(result) + + def test_as_invoke_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.invoke + + # Act + result = activity.as_invoke_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.invoke) + + def test_as_invoke_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_invoke_activity() + + # Assert + self.assertIsNone(result) + + def test_as_message_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_message_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.message) + + def test_as_message_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.invoke + + # Act + result = activity.as_message_activity() + + # Assert + self.assertIsNone(result) + + def test_as_message_activity_type_none(self): + # Arrange + activity = self.__create_activity() + activity.type = None + + # Act + result = activity.as_message_activity() + + # Assert + self.assertIsNone(result) + + def test_as_message_delete_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message_delete + + # Act + result = activity.as_message_delete_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.message_delete) + + def test_as_message_delete_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_message_delete_activity() + + # Assert + self.assertIsNone(result) + + def test_as_message_reaction_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message_reaction + + # Act + result = activity.as_message_reaction_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.message_reaction) + + def test_as_message_reaction_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_message_reaction_activity() + + # Assert + self.assertIsNone(result) + + def test_as_message_update_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message_update + + # Act + result = activity.as_message_update_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.message_update) + + def test_as_message_update_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_message_update_activity() + + # Assert + self.assertIsNone(result) + + def test_as_suggestion_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.suggestion + + # Act + result = activity.as_suggestion_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.suggestion) + + def test_as_suggestion_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_suggestion_activity() + + # Assert + self.assertIsNone(result) + + def test_as_trace_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.trace + + # Act + result = activity.as_trace_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.trace) + + def test_as_trace_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_trace_activity() + + # Assert + self.assertIsNone(result) + + def test_as_typing_activity_return_activity(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.typing + + # Act + result = activity.as_typing_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.typing) + + def test_as_typing_activity_return_none(self): + # Arrange + activity = self.__create_activity() + activity.type = ActivityTypes.message + + # Act + result = activity.as_typing_activity() + + # Assert + self.assertIsNone(result) + + def test_create_contact_relation_update_activity(self): + # Act + result = Activity.create_contact_relation_update_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.contact_relation_update) + + def test_create_conversation_update_activity(self): + # Act + result = Activity.create_conversation_update_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.conversation_update) + + def test_create_end_of_conversation_activity(self): + # Act + result = Activity.create_end_of_conversation_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.end_of_conversation) + + def test_create_event_activity(self): + # Act + result = Activity.create_event_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.event) + + def test_create_handoff_activity(self): + # Act + result = Activity.create_handoff_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.handoff) + + def test_create_invoke_activity(self): + # Act + result = Activity.create_invoke_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.invoke) + + def test_create_message_activity(self): + # Act + result = Activity.create_message_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.message) + + def test_create_reply(self): + # Arrange + activity = self.__create_activity() + text = "test reply" + locale = "en-us" + + # Act + result = activity.create_reply(text=text, locale=locale) + + # Assert + self.assertEqual(result.text, text) + self.assertEqual(result.locale, locale) + self.assertEqual(result.type, ActivityTypes.message) + + def test_create_reply_without_arguments(self): + # Arrange + activity = self.__create_activity() + + # Act + result = activity.create_reply() + + # Assert + self.assertEqual(result.type, ActivityTypes.message) + self.assertEqual(result.text, "") + self.assertEqual(result.locale, activity.locale) + + def test_create_trace(self): + # Arrange + activity = self.__create_activity() + name = "test-activity" + value_type = "string" + value = "test-value" + label = "test-label" + + # Act + result = activity.create_trace( + name=name, value_type=value_type, value=value, label=label + ) + + # Assert + self.assertEqual(result.type, ActivityTypes.trace) + self.assertEqual(result.name, name) + self.assertEqual(result.value_type, value_type) + self.assertEqual(result.value, value) + self.assertEqual(result.label, label) + + def test_create_trace_activity_no_recipient(self): + # Arrange + activity = self.__create_activity() + activity.recipient = None + + # Act + result = activity.create_trace("test") + + # Assert + self.assertIsNone(result.from_property.id) + self.assertIsNone(result.from_property.name) + + def test_crete_trace_activity_no_value_type(self): + # Arrange + name = "test-activity" + value = "test-value" + label = "test-label" + + # Act + result = Activity.create_trace_activity(name=name, value=value, label=label) + + # Assert + self.assertEqual(result.type, ActivityTypes.trace) + self.assertEqual(result.value_type, type(value)) + self.assertEqual(result.label, label) + + def test_create_trace_activity(self): + # Arrange + name = "test-activity" + value_type = "string" + value = "test-value" + label = "test-label" + + # Act + result = Activity.create_trace_activity( + name=name, value_type=value_type, value=value, label=label + ) + + # Assert + self.assertEqual(result.type, ActivityTypes.trace) + self.assertEqual(result.name, name) + self.assertEqual(result.value_type, value_type) + self.assertEqual(result.label, label) + + def test_create_typing_activity(self): + # Act + result = Activity.create_typing_activity() + + # Assert + self.assertEqual(result.type, ActivityTypes.typing) + + def test_get_conversation_reference(self): + # Arrange + activity = self.__create_activity() + + # Act + result = activity.get_conversation_reference() + + # Assert + self.assertEqual(activity.id, result.activity_id) + self.assertEqual(activity.from_property.id, result.user.id) + self.assertEqual(activity.recipient.id, result.bot.id) + self.assertEqual(activity.conversation.id, result.conversation.id) + self.assertEqual(activity.channel_id, result.channel_id) + self.assertEqual(activity.locale, result.locale) + self.assertEqual(activity.service_url, result.service_url) + + def test_get_mentions(self): + # Arrange + mentions = [Entity(type="mention"), Entity(type="reaction")] + activity = Activity(entities=mentions) + + # Act + result = Activity.get_mentions(activity) + + # Assert + self.assertEqual(len(result), 1) + self.assertEqual(result[0].type, "mention") + + def test_get_reply_conversation_reference(self): + # Arrange + activity = self.__create_activity() + reply = ResourceResponse(id="1234") + + # Act + result = activity.get_reply_conversation_reference(reply=reply) + + # Assert + self.assertEqual(reply.id, result.activity_id) + self.assertEqual(activity.from_property.id, result.user.id) + self.assertEqual(activity.recipient.id, result.bot.id) + self.assertEqual(activity.conversation.id, result.conversation.id) + self.assertEqual(activity.channel_id, result.channel_id) + self.assertEqual(activity.locale, result.locale) + self.assertEqual(activity.service_url, result.service_url) + + def test_has_content_empty(self): + # Arrange + activity_empty = Activity() + + # Act + result_empty = activity_empty.has_content() + + # Assert + self.assertEqual(result_empty, False) + + def test_has_content_with_text(self): + # Arrange + activity_with_text = Activity(text="test-text") + + # Act + result_with_text = activity_with_text.has_content() + + # Assert + self.assertEqual(result_with_text, True) + + def test_has_content_with_summary(self): + # Arrange + activity_with_summary = Activity(summary="test-summary") + + # Act + result_with_summary = activity_with_summary.has_content() + + # Assert + self.assertEqual(result_with_summary, True) + + def test_has_content_with_attachment(self): + # Arrange + activity_with_attachment = Activity(attachments=[Attachment()]) + + # Act + result_with_attachment = activity_with_attachment.has_content() + + # Assert + self.assertEqual(result_with_attachment, True) + + def test_has_content_with_channel_data(self): + # Arrange + activity_with_channel_data = Activity(channel_data="test-channel-data") + + # Act + result_with_channel_data = activity_with_channel_data.has_content() + + # Assert + self.assertEqual(result_with_channel_data, True) + + def test_is_from_streaming_connection(self): + # Arrange + non_streaming = [ + "http://yayay.com", + "https://yayay.com", + "HTTP://yayay.com", + "HTTPS://yayay.com", + ] + streaming = [ + "urn:botframework:WebSocket:wss://beep.com", + "urn:botframework:WebSocket:http://beep.com", + "URN:botframework:WebSocket:wss://beep.com", + "URN:botframework:WebSocket:http://beep.com", + ] + activity = self.__create_activity() + activity.service_url = None + + # Assert + self.assertEqual(activity.is_from_streaming_connection(), False) + + for s in non_streaming: + activity.service_url = s + self.assertEqual(activity.is_from_streaming_connection(), False) + + for s in streaming: + activity.service_url = s + self.assertEqual(activity.is_from_streaming_connection(), True) + + @staticmethod + def __create_activity() -> Activity: + account1 = ChannelAccount( + id="ChannelAccount_Id_1", + name="ChannelAccount_Name_1", + aad_object_id="ChannelAccount_aadObjectId_1", + role="ChannelAccount_Role_1", + ) + + account2 = ChannelAccount( + id="ChannelAccount_Id_2", + name="ChannelAccount_Name_2", + aad_object_id="ChannelAccount_aadObjectId_2", + role="ChannelAccount_Role_2", + ) + + conversation_account = ConversationAccount( + conversation_type="a", + id="123", + is_group=True, + name="Name", + role="ConversationAccount_Role", + ) + + activity = Activity( + id="123", + from_property=account1, + recipient=account2, + conversation=conversation_account, + channel_id="ChannelId123", + locale="en-uS", + service_url="ServiceUrl123", + ) + + return activity
[Parity] ActivityEx is not present in Botbuilder-Python See [dotnet source](https://github.com/microsoft/botbuilder-js/issues/1753)
This item is assigned to @JuanAr from Southworks. Having problems with Github at the moment. @JuanAr @mrivera-ms @gabog Given that Class Exentions are a C# only feature we don't have a direct file equivalent but the functionality is probably in the actual class or a helper. Is there any specif functionality missing? @axelsrz I believe that in many cases, the pattern for Python would be to add the missing methods to the Activity class. That's correct @tracyboehrer, we have ActivityEx in dotnet because that was generated from swagger (and it was a partial class) but moving forward we should just start adding new methods to the main class and drop the partials for the generated ones (we'll get to that at some point in dotnet)
2020-06-26T21:38:35
microsoft/botbuilder-python
1,190
microsoft__botbuilder-python-1190
[ "1188" ]
454cc32384d7cb6c17f6f43d74ec0723d0fbe782
diff --git a/libraries/botbuilder-ai/setup.py b/libraries/botbuilder-ai/setup.py --- a/libraries/botbuilder-ai/setup.py +++ b/libraries/botbuilder-ai/setup.py @@ -39,6 +39,7 @@ "botbuilder.ai.luis", "botbuilder.ai.qna.models", "botbuilder.ai.qna.utils", + "botbuilder.ai.qna.dialogs", ], install_requires=REQUIRES + TESTS_REQUIRES, tests_require=TESTS_REQUIRES,
No module named 'botbuilder.ai.qna.dialogs' - Python QnA Sample 49 ## Version botbuilder-ai - 4.9.1 ## Describe the bug I was trying out the QnA Maker Sample - 49.qnamaker-all-features . I've configured my QnA KB and also the config.py with the necessary info. However the module botbuilder.ai.qna.dialogs does not seem to exist. I've manually verified for the class QnAMakermDialog and it does not exist > from botbuilder.ai.qna.dialogs import QnAMakermDialog ## To Reproduce Steps to reproduce the behavior: 1. Download the sample 49.qnamaker-all-features 2. Install the necessary requirements and configure QnAMaker. 3. Run python app.py in the folder ## Expected behavior The sample should've run successfully. [bug]
@vijaysaimutyala Where are you seeing that import line? The actual class name should be QnAMakerDialog (not QnAMakermDialog). @tracyboehrer Sorry that might be a typo. You can look the import [here](https://github.com/microsoft/BotBuilder-Samples/blob/master/samples/python/49.qnamaker-all-features/app.py) I rectified the typo and still couldn't see the module. Below is the screenshot from my local env. I'm somehow missing the dialogs part I see on the Botbuilder-python [repo](https://github.com/microsoft/botbuilder-python/tree/c15c61523c4b69f81bddbfd49e1be910beca0cdd/libraries/botbuilder-ai/botbuilder/ai/qna/dialogs) ![image](https://user-images.githubusercontent.com/7084628/86011594-7f031780-ba3a-11ea-86d5-5b205d75a869.png) I tried updating botbuilder-ai, but its already at 4.9.1 A quick update. I created a fresh conda environment and installed the requirements of the [sample 49](https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/python/49.qnamaker-all-features) but I faced the same issue again. Also I noticed on the Samples homepage that the Python sample link is not updated yet. ![image](https://user-images.githubusercontent.com/7084628/86012756-fd13ee00-ba3b-11ea-9caa-c46415d7d652.png) @vijaysaimutyala This is a bug on our side. We didn't provide an export for the dialogs package. Thanks for checking @tracyboehrer Let me know if I can help in any way.
2020-06-29T18:24:54
microsoft/botbuilder-python
1,196
microsoft__botbuilder-python-1196
[ "1122" ]
496a8847693539665bcf76239fcaea0c423172f3
diff --git a/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py b/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py --- a/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py +++ b/libraries/botbuilder-schema/botbuilder/schema/_models_py3.py @@ -1196,6 +1196,8 @@ class CardAction(Model): :type value: object :param channel_data: Channel-specific data associated with this action :type channel_data: object + :param image_alt_text: Alternate image text to be used in place of the `image` field + :type image_alt_text: str """ _attribute_map = { @@ -1206,6 +1208,7 @@ class CardAction(Model): "display_text": {"key": "displayText", "type": "str"}, "value": {"key": "value", "type": "object"}, "channel_data": {"key": "channelData", "type": "object"}, + "image_alt_text": {"key": "imageAltText", "type": "str"}, } def __init__( @@ -1218,6 +1221,7 @@ def __init__( display_text: str = None, value=None, channel_data=None, + image_alt_text: str = None, **kwargs ) -> None: super(CardAction, self).__init__(**kwargs) @@ -1228,6 +1232,7 @@ def __init__( self.display_text = display_text self.value = value self.channel_data = channel_data + self.image_alt_text = image_alt_text class CardImage(Model):
Update CardAction to support alt text for images on buttons See [parent](https://github.com/microsoft/botframework-sdk/issues/5874)
2020-06-30T15:10:45
microsoft/botbuilder-python
1,205
microsoft__botbuilder-python-1205
[ "941" ]
7ca4369977732746c95d07a04c94b1385747522e
diff --git a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_payload.py b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_payload.py --- a/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_payload.py +++ b/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_payload.py @@ -15,6 +15,12 @@ def __init__(self, **kwargs): self.team: str = kwargs.get("team") self.user: str = kwargs.get("user") self.actions: Optional[List[Action]] = None + self.trigger_id: str = kwargs.get("trigger_id") + self.action_ts: str = kwargs.get("action_ts") + self.submission: str = kwargs.get("submission") + self.callback_id: str = kwargs.get("callback_id") + self.state: str = kwargs.get("state") + self.response_url: str = kwargs.get("response_url") if "message" in kwargs: message = kwargs.get("message")
[PORT] Slack adapter updates for dialog interactions > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3744 Fixes #3733 #3726 #3725 #3724 * Adds missing values to SlackPayload model * Expose SlackClientWrapper via public property # Changed projects * Adapters
2020-07-01T15:21:18
microsoft/botbuilder-python
1,207
microsoft__botbuilder-python-1207
[ "1199" ]
58b3b46c43175546ed3312233e1c6a7955e5342d
diff --git a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/channel.py b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/channel.py --- a/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/channel.py +++ b/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/channel.py @@ -32,7 +32,6 @@ def supports_suggested_actions(channel_id: str, button_cnt: int = 100) -> bool: # https://dev.kik.com/#/docs/messaging#text-response-object Channels.kik: 20, Channels.telegram: 100, - Channels.slack: 100, Channels.emulator: 100, Channels.direct_line: 100, Channels.webchat: 100,
[PORT] Remove Slack from the list of channels that support Suggested Actions > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/4177 Fixes #2291 Removing Slack from the list of channels that do not support suggested actions. # Changed projects * Microsoft.Bot.Builder.Dialogs
2020-07-01T15:26:25
microsoft/botbuilder-python
1,212
microsoft__botbuilder-python-1212
[ "1143" ]
5c30a004cc92dbfc5763d38474c2d57bc2e0e945
diff --git a/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py b/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py --- a/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py +++ b/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py @@ -28,6 +28,19 @@ class TeamsActivityHandler(ActivityHandler): async def on_invoke_activity(self, turn_context: TurnContext) -> InvokeResponse: + """ + Invoked when an invoke activity is received from the connector. + Invoke activities can be used to communicate many different things. + + :param turn_context: A context object for this turn. + + :returns: An InvokeResponse that represents the work queued to execute. + + .. remarks:: + Invoke activities communicate programmatic commands from a client or channel to a bot. + The meaning of an invoke activity is defined by the "invoke_activity.name" property, + which is meaningful within the scope of a channel. + """ try: if ( not turn_context.activity.name @@ -154,14 +167,35 @@ async def on_invoke_activity(self, turn_context: TurnContext) -> InvokeResponse: return invoke_exception.create_invoke_response() async def on_sign_in_invoke(self, turn_context: TurnContext): + """ + Invoked when a signIn invoke activity is received from the connector. + + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ return await self.on_teams_signin_verify_state(turn_context) async def on_teams_card_action_invoke( self, turn_context: TurnContext ) -> InvokeResponse: + """ + Invoked when an card action invoke activity is received from the connector. + + :param turn_context: A context object for this turn. + + :returns: An InvokeResponse that represents the work queued to execute. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_signin_verify_state(self, turn_context: TurnContext): + """ + Invoked when a signIn verify state activity is received from the connector. + + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_signin_token_exchange(self, turn_context: TurnContext): @@ -172,6 +206,15 @@ async def on_teams_file_consent( turn_context: TurnContext, file_consent_card_response: FileConsentCardResponse, ) -> InvokeResponse: + """ + Invoked when a file consent card activity is received from the connector. + + :param turn_context: A context object for this turn. + :param file_consent_card_response: The response representing the value of the invoke + activity sent when the user acts on a file consent card. + + :returns: An InvokeResponse depending on the action of the file consent card. + """ if file_consent_card_response.action == "accept": await self.on_teams_file_consent_accept( turn_context, file_consent_card_response @@ -194,6 +237,15 @@ async def on_teams_file_consent_accept( # pylint: disable=unused-argument turn_context: TurnContext, file_consent_card_response: FileConsentCardResponse, ): + """ + Invoked when a file consent card is accepted by the user. + + :param turn_context: A context object for this turn. + :param file_consent_card_response: The response representing the value of the invoke + activity sent when the user accepts a file consent card. + + :returns: A task that represents the work queued to execute. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_file_consent_decline( # pylint: disable=unused-argument @@ -201,31 +253,80 @@ async def on_teams_file_consent_decline( # pylint: disable=unused-argument turn_context: TurnContext, file_consent_card_response: FileConsentCardResponse, ): + """ + Invoked when a file consent card is declined by the user. + + :param turn_context: A context object for this turn. + :param file_consent_card_response: The response representing the value of the invoke + activity sent when the user declines a file consent card. + + :returns: A task that represents the work queued to execute. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_o365_connector_card_action( # pylint: disable=unused-argument self, turn_context: TurnContext, query: O365ConnectorCardActionQuery ): + """ + Invoked when a O365 Connector Card Action activity is received from the connector. + + :param turn_context: A context object for this turn. + :param query: The O365 connector card HttpPOST invoke query. + + :returns: A task that represents the work queued to execute. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_app_based_link_query( # pylint: disable=unused-argument self, turn_context: TurnContext, query: AppBasedLinkQuery ) -> MessagingExtensionResponse: + """ + Invoked when an app based link query activity is received from the connector. + + :param turn_context: A context object for this turn. + :param query: The invoke request body type for app-based link query. + + :returns: The Messaging Extension Response for the query. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_messaging_extension_query( # pylint: disable=unused-argument self, turn_context: TurnContext, query: MessagingExtensionQuery ) -> MessagingExtensionResponse: + """ + Invoked when a Messaging Extension Query activity is received from the connector. + + :param turn_context: A context object for this turn. + :param query: The query for the search command. + + :returns: The Messaging Extension Response for the query. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_messaging_extension_select_item( # pylint: disable=unused-argument self, turn_context: TurnContext, query ) -> MessagingExtensionResponse: + """ + Invoked when a messaging extension select item activity is received from the connector. + + :param turn_context: A context object for this turn. + :param query: The object representing the query. + + :returns: The Messaging Extension Response for the query. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_messaging_extension_submit_action_dispatch( self, turn_context: TurnContext, action: MessagingExtensionAction ) -> MessagingExtensionActionResponse: + """ + Invoked when a messaging extension submit action dispatch activity is received from the connector. + + :param turn_context: A context object for this turn. + :param action: The messaging extension action. + + :returns: The Messaging Extension Action Response for the action. + """ if not action.bot_message_preview_action: return await self.on_teams_messaging_extension_submit_action( turn_context, action @@ -249,50 +350,135 @@ async def on_teams_messaging_extension_submit_action_dispatch( async def on_teams_messaging_extension_bot_message_preview_edit( # pylint: disable=unused-argument self, turn_context: TurnContext, action: MessagingExtensionAction ) -> MessagingExtensionActionResponse: + """ + Invoked when a messaging extension bot message preview edit activity is received from the connector. + + :param turn_context: A context object for this turn. + :param action: The messaging extension action. + + :returns: The Messaging Extension Action Response for the action. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_messaging_extension_bot_message_preview_send( # pylint: disable=unused-argument self, turn_context: TurnContext, action: MessagingExtensionAction ) -> MessagingExtensionActionResponse: + """ + Invoked when a messaging extension bot message preview send activity is received from the connector. + + :param turn_context: A context object for this turn. + :param action: The messaging extension action. + + :returns: The Messaging Extension Action Response for the action. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_messaging_extension_submit_action( # pylint: disable=unused-argument self, turn_context: TurnContext, action: MessagingExtensionAction ) -> MessagingExtensionActionResponse: + """ + Invoked when a messaging extension submit action activity is received from the connector. + + :param turn_context: A context object for this turn. + :param action: The messaging extension action. + + :returns: The Messaging Extension Action Response for the action. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_messaging_extension_fetch_task( # pylint: disable=unused-argument self, turn_context: TurnContext, action: MessagingExtensionAction ) -> MessagingExtensionActionResponse: + """ + Invoked when a Messaging Extension Fetch activity is received from the connector. + + :param turn_context: A context object for this turn. + :param action: The messaging extension action. + + :returns: The Messaging Extension Action Response for the action. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_messaging_extension_configuration_query_settings_url( # pylint: disable=unused-argument self, turn_context: TurnContext, query: MessagingExtensionQuery ) -> MessagingExtensionResponse: + """ + Invoked when a messaging extension configuration query setting url activity is received from the connector. + + :param turn_context: A context object for this turn. + :param query: The Messaging extension query. + + :returns: The Messaging Extension Response for the query. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_messaging_extension_configuration_setting( # pylint: disable=unused-argument self, turn_context: TurnContext, settings ): + """ + Override this in a derived class to provide logic for when a configuration is set for a messaging extension. + + :param turn_context: A context object for this turn. + :param settings: Object representing the configuration settings. + + :returns: A task that represents the work queued to execute. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_messaging_extension_card_button_clicked( # pylint: disable=unused-argument self, turn_context: TurnContext, card_data ): + """ + Override this in a derived class to provide logic for when a card button is clicked in a messaging extension. + + :param turn_context: A context object for this turn. + :param card_data: Object representing the card data. + + :returns: A task that represents the work queued to execute. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_task_module_fetch( # pylint: disable=unused-argument self, turn_context: TurnContext, task_module_request: TaskModuleRequest ) -> TaskModuleResponse: + """ + Override this in a derived class to provide logic for when a task module is fetched. + + :param turn_context: A context object for this turn. + :param task_module_request: The task module invoke request value payload. + + :returns: A Task Module Response for the request. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_teams_task_module_submit( # pylint: disable=unused-argument self, turn_context: TurnContext, task_module_request: TaskModuleRequest ) -> TaskModuleResponse: + """ + Override this in a derived class to provide logic for when a task module is submitted. + + :param turn_context: A context object for this turn. + :param task_module_request: The task module invoke request value payload. + + :returns: A Task Module Response for the request. + """ raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED) async def on_conversation_update_activity(self, turn_context: TurnContext): + """ + Invoked when a conversation update activity is received from the channel. + Conversation update activities are useful when it comes to responding to users + being added to or removed from the channel. + For example, a bot could respond to a user being added by greeting the user. + + :param turn_context: A context object for this turn. + :returns: A task that represents the work queued to execute. + + .. remarks:: + In a derived class, override this method to add logic that applies + to all conversation update activities. + """ if turn_context.activity.channel_id == Channels.ms_teams: channel_data = TeamsChannelData().deserialize( turn_context.activity.channel_data @@ -324,6 +510,10 @@ async def on_conversation_update_activity(self, turn_context: TurnContext): return await self.on_teams_channel_renamed( channel_data.channel, channel_data.team, turn_context ) + if channel_data.event_type == "channelRestored": + return await self.on_teams_channel_restored( + channel_data.channel, channel_data.team, turn_context + ) if channel_data.event_type == "teamRenamed": return await self.on_teams_team_renamed_activity( channel_data.team, turn_context @@ -334,11 +524,30 @@ async def on_conversation_update_activity(self, turn_context: TurnContext): async def on_teams_channel_created( # pylint: disable=unused-argument self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext ): + """ + Invoked when a Channel Created event activity is received from the connector. + Channel Created correspond to the user creating a new channel. + + :param channel_info: The channel info object which describes the channel. + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ return async def on_teams_team_renamed_activity( # pylint: disable=unused-argument self, team_info: TeamInfo, turn_context: TurnContext ): + """ + Invoked when a Team Renamed event activity is received from the connector. + Team Renamed correspond to the user renaming an existing team. + + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ return async def on_teams_members_added_dispatch( # pylint: disable=unused-argument @@ -347,7 +556,18 @@ async def on_teams_members_added_dispatch( # pylint: disable=unused-argument team_info: TeamInfo, turn_context: TurnContext, ): - + """ + Override this in a derived class to provide logic for when members other than the bot + join the channel, such as your bot's welcome logic. + It will get the associated members with the provided accounts. + + :param members_added: A list of all the accounts added to the channel, as + described by the conversation update activity. + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ team_members_added = [] for member in members_added: is_bot = ( @@ -389,6 +609,17 @@ async def on_teams_members_added( # pylint: disable=unused-argument team_info: TeamInfo, turn_context: TurnContext, ): + """ + Override this in a derived class to provide logic for when members other than the bot + join the channel, such as your bot's welcome logic. + + :param teams_members_added: A list of all the members added to the channel, as + described by the conversation update activity. + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ teams_members_added = [ ChannelAccount().deserialize(member.serialize()) for member in teams_members_added @@ -403,6 +634,18 @@ async def on_teams_members_removed_dispatch( # pylint: disable=unused-argument team_info: TeamInfo, turn_context: TurnContext, ): + """ + Override this in a derived class to provide logic for when members other than the bot + leave the channel, such as your bot's good-bye logic. + It will get the associated members with the provided accounts. + + :param members_removed: A list of all the accounts removed from the channel, as + described by the conversation update activity. + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ teams_members_removed = [] for member in members_removed: new_account_json = member.serialize() @@ -422,6 +665,17 @@ async def on_teams_members_removed( # pylint: disable=unused-argument team_info: TeamInfo, turn_context: TurnContext, ): + """ + Override this in a derived class to provide logic for when members other than the bot + leave the channel, such as your bot's good-bye logic. + + :param teams_members_removed: A list of all the members removed from the channel, as + described by the conversation update activity. + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ members_removed = [ ChannelAccount().deserialize(member.serialize()) for member in teams_members_removed @@ -431,9 +685,44 @@ async def on_teams_members_removed( # pylint: disable=unused-argument async def on_teams_channel_deleted( # pylint: disable=unused-argument self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext ): + """ + Invoked when a Channel Deleted event activity is received from the connector. + Channel Deleted correspond to the user deleting an existing channel. + + :param channel_info: The channel info object which describes the channel. + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ return async def on_teams_channel_renamed( # pylint: disable=unused-argument self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext ): + """ + Invoked when a Channel Renamed event activity is received from the connector. + Channel Renamed correspond to the user renaming an existing channel. + + :param channel_info: The channel info object which describes the channel. + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ + return + + async def on_teams_channel_restored( # pylint: disable=unused-argument + self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext + ): + """ + Invoked when a Channel Restored event activity is received from the connector. + Channel Restored correspond to the user restoring a previously deleted channel. + + :param channel_info: The channel info object which describes the channel. + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ return
diff --git a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py --- a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py +++ b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py @@ -100,6 +100,14 @@ async def on_teams_channel_renamed( channel_info, team_info, turn_context ) + async def on_teams_channel_restored( + self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext + ): + self.record.append("on_teams_channel_restored") + return await super().on_teams_channel_restored( + channel_info, team_info, turn_context + ) + async def on_teams_channel_deleted( self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext ): @@ -313,6 +321,28 @@ async def test_on_teams_channel_renamed_activity(self): assert bot.record[0] == "on_conversation_update_activity" assert bot.record[1] == "on_teams_channel_renamed" + async def test_on_teams_channel_restored_activity(self): + # arrange + activity = Activity( + type=ActivityTypes.conversation_update, + channel_data={ + "eventType": "channelRestored", + "channel": {"id": "asdfqwerty", "name": "channel_restored"}, + }, + channel_id=Channels.ms_teams, + ) + + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_channel_restored" + async def test_on_teams_channel_deleted_activity(self): # arrange activity = Activity(
Additional channel/chat lifecycle events (Python) See [parent](https://github.com/microsoft/botframework-sdk/issues/5892)
This item is assigned to @JuanAr from Southworks. Having problems with Github at the moment.
2020-07-01T20:27:33
microsoft/botbuilder-python
1,213
microsoft__botbuilder-python-1213
[ "1143" ]
c4f2a9334c6fd48d943f6bcabd7490c19456ab46
diff --git a/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py b/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py --- a/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py +++ b/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py @@ -1,6 +1,8 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +# pylint: disable=too-many-lines + from http import HTTPStatus from botbuilder.schema import ChannelAccount, ErrorResponseException, SignInConstants from botbuilder.core import ActivityHandler, InvokeResponse @@ -510,6 +512,18 @@ async def on_conversation_update_activity(self, turn_context: TurnContext): return await self.on_teams_channel_renamed( channel_data.channel, channel_data.team, turn_context ) + if channel_data.event_type == "teamArchived": + return await self.on_teams_team_archived( + channel_data.team, turn_context + ) + if channel_data.event_type == "teamDeleted": + return await self.on_teams_team_deleted( + channel_data.team, turn_context + ) + if channel_data.event_type == "teamHardDeleted": + return await self.on_teams_team_hard_deleted( + channel_data.team, turn_context + ) if channel_data.event_type == "channelRestored": return await self.on_teams_channel_restored( channel_data.channel, channel_data.team, turn_context @@ -518,6 +532,14 @@ async def on_conversation_update_activity(self, turn_context: TurnContext): return await self.on_teams_team_renamed_activity( channel_data.team, turn_context ) + if channel_data.event_type == "teamRestored": + return await self.on_teams_team_restored( + channel_data.team, turn_context + ) + if channel_data.event_type == "teamUnarchived": + return await self.on_teams_team_unarchived( + channel_data.team, turn_context + ) return await super().on_conversation_update_activity(turn_context) @@ -536,6 +558,48 @@ async def on_teams_channel_created( # pylint: disable=unused-argument """ return + async def on_teams_team_archived( # pylint: disable=unused-argument + self, team_info: TeamInfo, turn_context: TurnContext + ): + """ + Invoked when a Team Archived event activity is received from the connector. + Team Archived correspond to the user archiving a team. + + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ + return + + async def on_teams_team_deleted( # pylint: disable=unused-argument + self, team_info: TeamInfo, turn_context: TurnContext + ): + """ + Invoked when a Team Deleted event activity is received from the connector. + Team Deleted corresponds to the user deleting a team. + + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ + return + + async def on_teams_team_hard_deleted( # pylint: disable=unused-argument + self, team_info: TeamInfo, turn_context: TurnContext + ): + """ + Invoked when a Team Hard Deleted event activity is received from the connector. + Team Hard Deleted corresponds to the user hard deleting a team. + + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ + return + async def on_teams_team_renamed_activity( # pylint: disable=unused-argument self, team_info: TeamInfo, turn_context: TurnContext ): @@ -550,6 +614,34 @@ async def on_teams_team_renamed_activity( # pylint: disable=unused-argument """ return + async def on_teams_team_restored( # pylint: disable=unused-argument + self, team_info: TeamInfo, turn_context: TurnContext + ): + """ + Invoked when a Team Restored event activity is received from the connector. + Team Restored corresponds to the user restoring a team. + + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ + return + + async def on_teams_team_unarchived( # pylint: disable=unused-argument + self, team_info: TeamInfo, turn_context: TurnContext + ): + """ + Invoked when a Team Unarchived event activity is received from the connector. + Team Unarchived correspond to the user unarchiving a team. + + :param team_info: The team info object representing the team. + :param turn_context: A context object for this turn. + + :returns: A task that represents the work queued to execute. + """ + return + async def on_teams_members_added_dispatch( # pylint: disable=unused-argument self, members_added: [ChannelAccount],
diff --git a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py --- a/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py +++ b/libraries/botbuilder-core/tests/teams/test_teams_activity_handler.py @@ -1,5 +1,9 @@ -from typing import List +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +# pylint: disable=too-many-lines +from typing import List import aiounittest from botbuilder.core import BotAdapter, TurnContext from botbuilder.core.teams import TeamsActivityHandler @@ -116,12 +120,42 @@ async def on_teams_channel_deleted( channel_info, team_info, turn_context ) + async def on_teams_team_archived( + self, team_info: TeamInfo, turn_context: TurnContext + ): + self.record.append("on_teams_team_archived") + return await super().on_teams_team_archived(team_info, turn_context) + + async def on_teams_team_deleted( + self, team_info: TeamInfo, turn_context: TurnContext + ): + self.record.append("on_teams_team_deleted") + return await super().on_teams_team_deleted(team_info, turn_context) + + async def on_teams_team_hard_deleted( + self, team_info: TeamInfo, turn_context: TurnContext + ): + self.record.append("on_teams_team_hard_deleted") + return await super().on_teams_team_hard_deleted(team_info, turn_context) + async def on_teams_team_renamed_activity( self, team_info: TeamInfo, turn_context: TurnContext ): self.record.append("on_teams_team_renamed_activity") return await super().on_teams_team_renamed_activity(team_info, turn_context) + async def on_teams_team_restored( + self, team_info: TeamInfo, turn_context: TurnContext + ): + self.record.append("on_teams_team_restored") + return await super().on_teams_team_restored(team_info, turn_context) + + async def on_teams_team_unarchived( + self, team_info: TeamInfo, turn_context: TurnContext + ): + self.record.append("on_teams_team_unarchived") + return await super().on_teams_team_unarchived(team_info, turn_context) + async def on_invoke_activity(self, turn_context: TurnContext): self.record.append("on_invoke_activity") return await super().on_invoke_activity(turn_context) @@ -365,6 +399,72 @@ async def test_on_teams_channel_deleted_activity(self): assert bot.record[0] == "on_conversation_update_activity" assert bot.record[1] == "on_teams_channel_deleted" + async def test_on_teams_team_archived(self): + # arrange + activity = Activity( + type=ActivityTypes.conversation_update, + channel_data={ + "eventType": "teamArchived", + "team": {"id": "team_id_1", "name": "archived_team_name"}, + }, + channel_id=Channels.ms_teams, + ) + + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_team_archived" + + async def test_on_teams_team_deleted(self): + # arrange + activity = Activity( + type=ActivityTypes.conversation_update, + channel_data={ + "eventType": "teamDeleted", + "team": {"id": "team_id_1", "name": "deleted_team_name"}, + }, + channel_id=Channels.ms_teams, + ) + + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_team_deleted" + + async def test_on_teams_team_hard_deleted(self): + # arrange + activity = Activity( + type=ActivityTypes.conversation_update, + channel_data={ + "eventType": "teamHardDeleted", + "team": {"id": "team_id_1", "name": "hard_deleted_team_name"}, + }, + channel_id=Channels.ms_teams, + ) + + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_team_hard_deleted" + async def test_on_teams_team_renamed_activity(self): # arrange activity = Activity( @@ -387,6 +487,50 @@ async def test_on_teams_team_renamed_activity(self): assert bot.record[0] == "on_conversation_update_activity" assert bot.record[1] == "on_teams_team_renamed_activity" + async def test_on_teams_team_restored(self): + # arrange + activity = Activity( + type=ActivityTypes.conversation_update, + channel_data={ + "eventType": "teamRestored", + "team": {"id": "team_id_1", "name": "restored_team_name"}, + }, + channel_id=Channels.ms_teams, + ) + + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_team_restored" + + async def test_on_teams_team_unarchived(self): + # arrange + activity = Activity( + type=ActivityTypes.conversation_update, + channel_data={ + "eventType": "teamUnarchived", + "team": {"id": "team_id_1", "name": "unarchived_team_name"}, + }, + channel_id=Channels.ms_teams, + ) + + turn_context = TurnContext(NotImplementedAdapter(), activity) + + # Act + bot = TestingTeamsActivityHandler() + await bot.on_turn(turn_context) + + # Assert + assert len(bot.record) == 2 + assert bot.record[0] == "on_conversation_update_activity" + assert bot.record[1] == "on_teams_team_unarchived" + async def test_on_teams_members_added_activity(self): # arrange activity = Activity(
Additional channel/chat lifecycle events (Python) See [parent](https://github.com/microsoft/botframework-sdk/issues/5892)
This item is assigned to @JuanAr from Southworks. Having problems with Github at the moment.
2020-07-01T20:29:02
microsoft/botbuilder-python
1,219
microsoft__botbuilder-python-1219
[ "989" ]
a8377613f199331ef4b2baed1ef70ce00e88ff1f
diff --git a/libraries/botbuilder-core/botbuilder/core/bot_state.py b/libraries/botbuilder-core/botbuilder/core/bot_state.py --- a/libraries/botbuilder-core/botbuilder/core/bot_state.py +++ b/libraries/botbuilder-core/botbuilder/core/bot_state.py @@ -6,6 +6,7 @@ from typing import Callable, Dict, Union from jsonpickle.pickler import Pickler from botbuilder.core.state_property_accessor import StatePropertyAccessor +from .bot_assert import BotAssert from .turn_context import TurnContext from .storage import Storage from .property_manager import PropertyManager @@ -61,6 +62,18 @@ def __init__(self, storage: Storage, context_service_key: str): self._storage = storage self._context_service_key = context_service_key + def get_cached_state(self, turn_context: TurnContext): + """ + Gets the cached bot state instance that wraps the raw cached data for this "BotState" + from the turn context. + + :param turn_context: The context object for this turn. + :type turn_context: :class:`TurnContext` + :return: The cached bot state instance. + """ + BotAssert.context_not_none(turn_context) + return turn_context.turn_state.get(self._context_service_key) + def create_property(self, name: str) -> StatePropertyAccessor: """ Creates a property definition and registers it with this :class:`BotState`. @@ -75,7 +88,8 @@ def create_property(self, name: str) -> StatePropertyAccessor: return BotStatePropertyAccessor(self, name) def get(self, turn_context: TurnContext) -> Dict[str, object]: - cached = turn_context.turn_state.get(self._context_service_key) + BotAssert.context_not_none(turn_context) + cached = self.get_cached_state(turn_context) return getattr(cached, "state", None) @@ -88,10 +102,9 @@ async def load(self, turn_context: TurnContext, force: bool = False) -> None: :param force: Optional, true to bypass the cache :type force: bool """ - if turn_context is None: - raise TypeError("BotState.load(): turn_context cannot be None.") + BotAssert.context_not_none(turn_context) - cached_state = turn_context.turn_state.get(self._context_service_key) + cached_state = self.get_cached_state(turn_context) storage_key = self.get_storage_key(turn_context) if force or not cached_state or not cached_state.state: @@ -111,10 +124,9 @@ async def save_changes( :param force: Optional, true to save state to storage whether or not there are changes :type force: bool """ - if turn_context is None: - raise TypeError("BotState.save_changes(): turn_context cannot be None.") + BotAssert.context_not_none(turn_context) - cached_state = turn_context.turn_state.get(self._context_service_key) + cached_state = self.get_cached_state(turn_context) if force or (cached_state is not None and cached_state.is_changed): storage_key = self.get_storage_key(turn_context) @@ -134,8 +146,7 @@ async def clear_state(self, turn_context: TurnContext): .. remarks:: This function must be called in order for the cleared state to be persisted to the underlying store. """ - if turn_context is None: - raise TypeError("BotState.clear_state(): turn_context cannot be None.") + BotAssert.context_not_none(turn_context) # Explicitly setting the hash will mean IsChanged is always true. And that will force a Save. cache_value = CachedBotState() @@ -151,8 +162,7 @@ async def delete(self, turn_context: TurnContext) -> None: :return: None """ - if turn_context is None: - raise TypeError("BotState.delete(): turn_context cannot be None.") + BotAssert.context_not_none(turn_context) turn_context.turn_state.pop(self._context_service_key) @@ -174,15 +184,12 @@ async def get_property_value(self, turn_context: TurnContext, property_name: str :return: The value of the property """ - if turn_context is None: - raise TypeError( - "BotState.get_property_value(): turn_context cannot be None." - ) + BotAssert.context_not_none(turn_context) if not property_name: raise TypeError( "BotState.get_property_value(): property_name cannot be None." ) - cached_state = turn_context.turn_state.get(self._context_service_key) + cached_state = self.get_cached_state(turn_context) # if there is no value, this will throw, to signal to IPropertyAccesor that a default value should be computed # This allows this to work with value types @@ -201,11 +208,10 @@ async def delete_property_value( :return: None """ - if turn_context is None: - raise TypeError("BotState.delete_property(): turn_context cannot be None.") + BotAssert.context_not_none(turn_context) if not property_name: raise TypeError("BotState.delete_property(): property_name cannot be None.") - cached_state = turn_context.turn_state.get(self._context_service_key) + cached_state = self.get_cached_state(turn_context) del cached_state.state[property_name] async def set_property_value( @@ -223,11 +229,10 @@ async def set_property_value( :return: None """ - if turn_context is None: - raise TypeError("BotState.delete_property(): turn_context cannot be None.") + BotAssert.context_not_none(turn_context) if not property_name: raise TypeError("BotState.delete_property(): property_name cannot be None.") - cached_state = turn_context.turn_state.get(self._context_service_key) + cached_state = self.get_cached_state(turn_context) cached_state.state[property_name] = value
diff --git a/libraries/botbuilder-core/tests/test_bot_state.py b/libraries/botbuilder-core/tests/test_bot_state.py --- a/libraries/botbuilder-core/tests/test_bot_state.py +++ b/libraries/botbuilder-core/tests/test_bot_state.py @@ -473,13 +473,32 @@ async def test_bot_state_get(self): storage = MemoryStorage({}) - conversation_state = ConversationState(storage) + test_bot_state = BotStateForTest(storage) ( - await conversation_state.create_property("test-name").get( + await test_bot_state.create_property("test-name").get( turn_context, lambda: TestPocoState() ) ).value = "test-value" - result = conversation_state.get(turn_context) + result = test_bot_state.get(turn_context) assert result["test-name"].value == "test-value" + + async def test_bot_state_get_cached_state(self): + # pylint: disable=unnecessary-lambda + turn_context = TestUtilities.create_empty_context() + turn_context.activity.conversation = ConversationAccount(id="1234") + + storage = MemoryStorage({}) + + test_bot_state = BotStateForTest(storage) + ( + await test_bot_state.create_property("test-name").get( + turn_context, lambda: TestPocoState() + ) + ).value = "test-value" + + result = test_bot_state.get_cached_state(turn_context) + + assert result is not None + assert result == test_bot_state.get_cached_state(turn_context)
[PORT] Fix bot state so that the context service key is used consistently to access the cached state > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3727 Fixes #3643 A bot state class's "context service key" is used to access the cached bot state in the turn state collection. Because the context service key is usually the name of the type (e.g. "UserState") there were some cases where the SDK was just using the type name instead of the actual context service key. This fails when a bot state class has a context service key that's different from the name of the type, as my new tests show. ~~In the case of a bot state memory scope, I also fixed the code to not rely on reflection to access the cached bot state. `BotStateMemoryScope<T>.GetMemory` now accesses the bot state instance in the same way that `BotStateMemoryScope<T>.LoadAsync` and `BotStateMemoryScope<T>.SaveChangesAsync` do, and once it has the bot state instance it can simply call `BotState.Get`. Because the classes that call `GetMemory` are expecting a dictionary and not a JObject, I modified `BotState.Get` to return an `IDictionary<string, object>`. I believe this is an improvement because that's the form that the cached bot state is already in and there's no need to convert it to a JObject. While it may seem like a dangerous change, the only place that `BotState.Get` is used is in one InspectionMiddleware method, and if any customers are using it and expecting a JObject then the compiler will just tell them to convert it to a JObject on their end, so there won't be any surprising behavior changes. I'm confident that the code is better this way and I can't imagine this breaking anything because the tests are all passing.~~ I have discovered that the problems I was seeing in `BotStateMemoryScope<T>` were not about `GetMemory` returning a JObject instead of a dictionary, they were about `BotState.Get` returning a copy of the of the state, which means any modifications wouldn't persist. I have also discovered that my "best option" to fix `BotStateMemoryScope<T>` by having `Get` return the original dictionary instead of a JObject will not work because it violates the contract. I see four other options: 1. Create a new public `Get` method (with a different name) to return the actual dictionary instead of a copy 2. Create an internal `Get` method and have the Bot Builder assembly share its members with the dialogs library 3. Create a private `Get` method and have `BotStateMemoryScope<T>.GetMemory` access it using reflection 4. Don't create any new methods and have `BotStateMemoryScope<T>.GetMemory` use reflection twice I went with option 4 because it's the most similar to the way things are currently set up. The reason we need to use reflection twice is because the `CachedBotState` class is private and the context service key we need to access it is also private. EDIT: I've thought of a fifth option. Since bot state is meant to be accessed using bot state property accessors, we could try to rework the adaptive dialogs library to access bot state using bot state property accessors. This would probably represent significant work/changes so I would not attempt it without some kind of go-ahead from the SDK team. # Changed projects * Microsoft.Bot.Builder.Dialogs * Microsoft.Bot.Builder * Microsoft.Bot.Builder.Dialogs.Tests * Microsoft.Bot.Builder.Tests
2020-07-03T21:13:12
microsoft/botbuilder-python
1,220
microsoft__botbuilder-python-1220
[ "1021" ]
8b5d8aa7d3bc508463027e432f7bd582a33b17ba
diff --git a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/application_insights_telemetry_client.py b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/application_insights_telemetry_client.py --- a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/application_insights_telemetry_client.py +++ b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/application_insights_telemetry_client.py @@ -38,13 +38,18 @@ def __init__( instrumentation_key: str, telemetry_client: TelemetryClient = None, telemetry_processor: Callable[[object, object], bool] = None, + client_queue_size: int = None, ): self._instrumentation_key = instrumentation_key + self._client = ( telemetry_client if telemetry_client is not None else TelemetryClient(self._instrumentation_key) ) + if client_queue_size: + self._client.channel.queue.max_queue_length = client_queue_size + # Telemetry Processor processor = ( telemetry_processor
Complete the aiohttp ApplicationInsights implementation See also #673
2020-07-06T15:24:51
microsoft/botbuilder-python
1,221
microsoft__botbuilder-python-1221
[ "940" ]
30ccb991afd4d30c36b408c8ebff60baa813c7d8
diff --git a/libraries/botbuilder-core/botbuilder/core/telemetry_constants.py b/libraries/botbuilder-core/botbuilder/core/telemetry_constants.py --- a/libraries/botbuilder-core/botbuilder/core/telemetry_constants.py +++ b/libraries/botbuilder-core/botbuilder/core/telemetry_constants.py @@ -5,6 +5,7 @@ class TelemetryConstants: """Telemetry logger property names.""" + ATTACHMENTS_PROPERTY: str = "attachments" CHANNEL_ID_PROPERTY: str = "channelId" CONVERSATION_ID_PROPERTY: str = "conversationId" CONVERSATION_NAME_PROPERTY: str = "conversationName" diff --git a/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py b/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py --- a/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py +++ b/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py @@ -211,6 +211,10 @@ async def fill_send_event_properties( # Use the LogPersonalInformation flag to toggle logging PII data, text and user name are common examples if self.log_personal_information: + if activity.attachments and activity.attachments.strip(): + properties[ + TelemetryConstants.ATTACHMENTS_PROPERTY + ] = activity.attachments if activity.from_property.name and activity.from_property.name.strip(): properties[ TelemetryConstants.FROM_NAME_PROPERTY
[PORT] Update telemetry logger to include attachments > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3737 Addresses #1574 in JS repo (https://github.com/microsoft/botbuilder-js/issues/1574) Telemetry logger will now include the collection of any attachments sent with the activity, if the LogPersonalInformation flag is set to true. # Changed projects * Microsoft.Bot.Builder
2020-07-06T20:18:26
microsoft/botbuilder-python
1,227
microsoft__botbuilder-python-1227
[ "1046" ]
9ad53ee4f38b19d948a4a9c3a1bfa4f8f81c29ee
diff --git a/libraries/botbuilder-core/botbuilder/core/adapter_extensions.py b/libraries/botbuilder-core/botbuilder/core/adapter_extensions.py --- a/libraries/botbuilder-core/botbuilder/core/adapter_extensions.py +++ b/libraries/botbuilder-core/botbuilder/core/adapter_extensions.py @@ -1,7 +1,10 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +from warnings import warn + from botbuilder.core import ( BotAdapter, + BotState, Storage, RegisterClassMiddleware, UserState, @@ -23,6 +26,39 @@ def use_storage(adapter: BotAdapter, storage: Storage) -> BotAdapter: """ return adapter.use(RegisterClassMiddleware(storage)) + @staticmethod + def use_bot_state( + bot_adapter: BotAdapter, *bot_states: BotState, auto: bool = True + ) -> BotAdapter: + """ + Registers bot state object into the TurnContext. The botstate will be available via the turn context. + + :param bot_adapter: The BotAdapter on which to register the state objects. + :param bot_states: One or more BotState objects to register. + :return: The updated adapter. + """ + if not bot_states: + raise TypeError("At least one BotAdapter is required") + + for bot_state in bot_states: + bot_adapter.use( + RegisterClassMiddleware( + bot_state, AdapterExtensions.fullname(bot_state) + ) + ) + + if auto: + bot_adapter.use(AutoSaveStateMiddleware(bot_states)) + + return bot_adapter + + @staticmethod + def fullname(obj): + module = obj.__class__.__module__ + if module is None or module == str.__class__.__module__: + return obj.__class__.__name__ # Avoid reporting __builtin__ + return module + "." + obj.__class__.__name__ + @staticmethod def use_state( adapter: BotAdapter, @@ -31,7 +67,7 @@ def use_state( auto: bool = True, ) -> BotAdapter: """ - Registers user and conversation state objects with the adapter. These objects will be available via + [DEPRECATED] Registers user and conversation state objects with the adapter. These objects will be available via the turn context's `turn_state` property. :param adapter: The BotAdapter on which to register the state objects. @@ -40,6 +76,11 @@ def use_state( :param auto: True to automatically persist state each turn. :return: The BotAdapter """ + warn( + "This method is deprecated in 4.9. You should use the method .use_bot_state() instead.", + DeprecationWarning, + ) + if not adapter: raise TypeError("BotAdapter is required") diff --git a/libraries/botbuilder-core/botbuilder/core/register_class_middleware.py b/libraries/botbuilder-core/botbuilder/core/register_class_middleware.py --- a/libraries/botbuilder-core/botbuilder/core/register_class_middleware.py +++ b/libraries/botbuilder-core/botbuilder/core/register_class_middleware.py @@ -10,8 +10,9 @@ class RegisterClassMiddleware(Middleware): Middleware for adding an object to or registering a service with the current turn context. """ - def __init__(self, service): + def __init__(self, service, key: str = None): self.service = service + self._key = key async def on_turn( self, context: TurnContext, logic: Callable[[TurnContext], Awaitable] @@ -19,7 +20,8 @@ async def on_turn( # C# has TurnStateCollection with has overrides for adding items # to TurnState. Python does not. In C#'s case, there is an 'Add' # to handle adding object, and that uses the fully qualified class name. - context.turn_state[self.fullname(self.service)] = self.service + key = self._key or self.fullname(self.service) + context.turn_state[key] = self.service await logic() @staticmethod
diff --git a/libraries/botbuilder-dialogs/tests/test_dialogextensions.py b/libraries/botbuilder-dialogs/tests/test_dialogextensions.py --- a/libraries/botbuilder-dialogs/tests/test_dialogextensions.py +++ b/libraries/botbuilder-dialogs/tests/test_dialogextensions.py @@ -221,7 +221,7 @@ async def capture_eoc( logic, TestAdapter.create_conversation_reference(conversation_id) ) AdapterExtensions.use_storage(adapter, storage) - AdapterExtensions.use_state(adapter, user_state, convo_state) + AdapterExtensions.use_bot_state(adapter, user_state, convo_state) adapter.use(TranscriptLoggerMiddleware(ConsoleTranscriptLogger())) return TestFlow(None, adapter)
[PORT] Replace UseState() with UseBotState() > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3862 Fixes #3859 and use untyped params so that order and type are not fixed. Tweak RegisterMiddlewareClass so you can provide the key for the turnstate. # Changed projects * Microsoft.Bot.Builder.Dialogs.Adaptive.Testing * Microsoft.Bot.Builder * Microsoft.Bot.Builder.AI.QnA.Tests * Microsoft.Bot.Builder.Dialogs.Adaptive.Templates.Tests * Microsoft.Bot.Builder.Dialogs.Adaptive.Tests * Microsoft.Bot.Builder.Dialogs.Declarative.Tests * Microsoft.Bot.Builder.Dialogs.Tests * Microsoft.Bot.Builder.TestBot.Json *
This applies to AdapterExtensions, and callers of that method.
2020-07-07T18:14:33
microsoft/botbuilder-python
1,231
microsoft__botbuilder-python-1231
[ "1022" ]
da319239853f0e9d10b91c273d2aaa39cbb056f3
diff --git a/libraries/botframework-connector/botframework/connector/auth/government_constants.py b/libraries/botframework-connector/botframework/connector/auth/government_constants.py --- a/libraries/botframework-connector/botframework/connector/auth/government_constants.py +++ b/libraries/botframework-connector/botframework/connector/auth/government_constants.py @@ -15,9 +15,7 @@ class GovernmentConstants(ABC): TO CHANNEL FROM BOT: Login URL """ TO_CHANNEL_FROM_BOT_LOGIN_URL = ( - "https://login.microsoftonline.us/" - "cab8a31a-1906-4287-a0d8-4eef66b95f6e/" - "oauth2/v2.0/token" + "https://login.microsoftonline.us/MicrosoftServices.onmicrosoft.us" ) """
[PORT] [Authentication] updates to support Arlington > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3734 # Changed projects * Microsoft.Bot.Connector * Microsoft.Bot.Connector.Tests [R9]
2020-07-07T23:39:19
microsoft/botbuilder-python
1,240
microsoft__botbuilder-python-1240
[ "1137" ]
f26ad85b36908ceff012fa1ebbe6cb7b083ee336
diff --git a/libraries/botbuilder-core/botbuilder/core/skills/skill_handler.py b/libraries/botbuilder-core/botbuilder/core/skills/skill_handler.py --- a/libraries/botbuilder-core/botbuilder/core/skills/skill_handler.py +++ b/libraries/botbuilder-core/botbuilder/core/skills/skill_handler.py @@ -151,7 +151,14 @@ async def _process_activity( if not skill_conversation_reference: raise KeyError("SkillConversationReference not found") + if not skill_conversation_reference.conversation_reference: + raise KeyError("conversationReference not found") + + # If an activity is sent, return the ResourceResponse + resource_response: ResourceResponse = None + async def callback(context: TurnContext): + nonlocal resource_response context.turn_state[ SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY ] = skill_conversation_reference @@ -177,7 +184,7 @@ async def callback(context: TurnContext): self._apply_event_to_turn_context_activity(context, activity) await self._bot.on_turn(context) else: - await context.send_activity(activity) + resource_response = await context.send_activity(activity) await self._adapter.continue_conversation( skill_conversation_reference.conversation_reference, @@ -185,7 +192,11 @@ async def callback(context: TurnContext): claims_identity=claims_identity, audience=skill_conversation_reference.oauth_scope, ) - return ResourceResponse(id=str(uuid4())) + + if not resource_response: + resource_response = ResourceResponse(id=str(uuid4())) + + return resource_response @staticmethod def _apply_eoc_to_turn_context_activity(
diff --git a/libraries/botbuilder-core/tests/skills/test_skill_handler.py b/libraries/botbuilder-core/tests/skills/test_skill_handler.py --- a/libraries/botbuilder-core/tests/skills/test_skill_handler.py +++ b/libraries/botbuilder-core/tests/skills/test_skill_handler.py @@ -238,6 +238,42 @@ async def test_on_send_to_conversation(self): ) assert activity.caller_id is None + async def test_forwarding_on_send_to_conversation(self): + self._conversation_id = await self._test_id_factory.create_skill_conversation_id( + self._conversation_reference + ) + + resource_response_id = "rId" + + async def side_effect( + *arg_list, **args_dict + ): # pylint: disable=unused-argument + fake_context = Mock() + fake_context.turn_state = {} + fake_context.send_activity = MagicMock(return_value=Future()) + fake_context.send_activity.return_value.set_result( + ResourceResponse(id=resource_response_id) + ) + await arg_list[1](fake_context) + + mock_adapter = Mock() + mock_adapter.continue_conversation = side_effect + mock_adapter.send_activities = MagicMock(return_value=Future()) + mock_adapter.send_activities.return_value.set_result([]) + + sut = self.create_skill_handler_for_testing(mock_adapter) + + activity = Activity(type=ActivityTypes.message, attachments=[], entities=[]) + TurnContext.apply_conversation_reference(activity, self._conversation_reference) + + assert not activity.caller_id + + response = await sut.test_on_send_to_conversation( + self._claims_identity, self._conversation_id, activity + ) + + assert response.id is resource_response_id + async def test_on_reply_to_activity(self): self._conversation_id = await self._test_id_factory.create_skill_conversation_id( self._conversation_reference
SkillHandler doesn't return ResourceResponse when forwarding activities (Python) See [parent](https://github.com/microsoft/botframework-sdk/issues/5919)
2020-07-10T06:11:37
microsoft/botbuilder-python
1,241
microsoft__botbuilder-python-1241
[ "698" ]
f7eb120fab30582f1bd24b6e1f4c0240bf203e4f
diff --git a/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py b/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py --- a/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py +++ b/libraries/botbuilder-core/botbuilder/core/bot_framework_adapter.py @@ -1174,39 +1174,43 @@ async def get_sign_in_resource_from_user_and_credentials( ) -> SignInUrlResponse: if not connection_name: raise TypeError( - "BotFrameworkAdapter.get_sign_in_resource_from_user(): missing connection_name" + "BotFrameworkAdapter.get_sign_in_resource_from_user_and_credentials(): missing connection_name" ) - if ( - not turn_context.activity.from_property - or not turn_context.activity.from_property.id - ): - raise TypeError( - "BotFrameworkAdapter.get_sign_in_resource_from_user(): missing activity id" - ) - if user_id and turn_context.activity.from_property.id != user_id: + if not user_id: raise TypeError( - "BotFrameworkAdapter.get_sign_in_resource_from_user(): cannot get signin resource" - " for a user that is different from the conversation" + "BotFrameworkAdapter.get_sign_in_resource_from_user_and_credentials(): missing user_id" ) - client = await self._create_token_api_client( - turn_context, oauth_app_credentials - ) - conversation = TurnContext.get_conversation_reference(turn_context.activity) + activity = turn_context.activity - state = TokenExchangeState( + app_id = self.__get_app_id(turn_context) + token_exchange_state = TokenExchangeState( connection_name=connection_name, - conversation=conversation, - relates_to=turn_context.activity.relates_to, - ms_app_id=client.config.credentials.microsoft_app_id, + conversation=ConversationReference( + activity_id=activity.id, + bot=activity.recipient, + channel_id=activity.channel_id, + conversation=activity.conversation, + locale=activity.locale, + service_url=activity.service_url, + user=activity.from_property, + ), + relates_to=activity.relates_to, + ms_app_id=app_id, ) - final_state = base64.b64encode( - json.dumps(state.serialize()).encode(encoding="UTF-8", errors="strict") + state = base64.b64encode( + json.dumps(token_exchange_state.serialize()).encode( + encoding="UTF-8", errors="strict" + ) ).decode() + client = await self._create_token_api_client( + turn_context, oauth_app_credentials + ) + return client.bot_sign_in.get_sign_in_resource( - final_state, final_redirect=final_redirect + state, final_redirect=final_redirect ) async def exchange_token(
Add support for skill OAuthCard to Emulator and WebChat (Python) See [parent Issue](https://github.com/microsoft/botframework-sdk/issues/5654)
2020-07-10T15:29:56
microsoft/botbuilder-python
1,244
microsoft__botbuilder-python-1244
[ "673" ]
77c3ac6989fc07beca3de90f33df3f7bce9ab53f
diff --git a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/processor/telemetry_processor.py b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/processor/telemetry_processor.py --- a/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/processor/telemetry_processor.py +++ b/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/processor/telemetry_processor.py @@ -1,7 +1,9 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +import base64 import json from abc import ABC, abstractmethod +from _sha256 import sha256 class TelemetryProcessor(ABC): @@ -11,8 +13,9 @@ class TelemetryProcessor(ABC): def activity_json(self) -> json: """Retrieve the request body as json (Activity).""" body_text = self.get_request_body() - body = json.loads(body_text) if body_text is not None else None - return body + if body_text: + return body_text if isinstance(body_text, dict) else json.loads(body_text) + return None @abstractmethod def can_process(self) -> bool: @@ -67,15 +70,34 @@ def __call__(self, data, context) -> bool: conversation = ( post_data["conversation"] if "conversation" in post_data else None ) - conversation_id = conversation["id"] if "id" in conversation else None + + session_id = "" + if "id" in conversation: + conversation_id = conversation["id"] + session_id = base64.b64encode( + sha256(conversation_id.encode("utf-8")).digest() + ).decode() + + # Set the user id on the Application Insights telemetry item. context.user.id = channel_id + user_id - context.session.id = conversation_id - # Additional bot-specific properties + # Set the session id on the Application Insights telemetry item. + # Hashed ID is used due to max session ID length for App Insights session Id + context.session.id = session_id + + # Set the activity id: + # https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#id if "id" in post_data: data.properties["activityId"] = post_data["id"] + + # Set the channel id: + # https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#channel-id if "channelId" in post_data: data.properties["channelId"] = post_data["channelId"] + + # Set the activity type: + # https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#type if "type" in post_data: data.properties["activityType"] = post_data["type"] + return True
[PORT] Implement hash for App Insights session ID > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/3317 Addresses this issue reported in JS https://github.com/microsoft/botbuilder-js/issues/1512 App Insights has a maximum session ID of 64 characters, but in some instances for some channels (such as reported with Teams) this may be exceeded due to conversation ID currently being used for session ID. This PR hashes the conversation ID and sets this as the session ID. It also adds an additional telemetry property to ensure we retain the original conversation ID within the telemetry. The hashed ID is only used for Application Insights and the original conversation ID and activity are left untouched. # Changed projects * integration
Note: This takes place in telemetry_processor.py in Python. Method get_request_body See: botframework\dotnet\libraries\integration\Microsoft.Bot.Builder.Integration.ApplicationInsights.Core\TelemetryBotIdInitializer.cs
2020-07-13T14:06:23
microsoft/botbuilder-python
1,251
microsoft__botbuilder-python-1251
[ "1246" ]
985969d9cc2fdae274a54ca68b4b220250c4f868
diff --git a/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py b/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py --- a/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py +++ b/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py @@ -1,9 +1,11 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """Middleware Component for logging Activity messages.""" - from typing import Awaitable, Callable, List, Dict from botbuilder.schema import Activity, ConversationReference, ActivityTypes +from botbuilder.schema.teams import TeamsChannelData, TeamInfo +from botframework.connector import Channels + from .bot_telemetry_client import BotTelemetryClient from .bot_assert import BotAssert from .middleware_set import Middleware @@ -183,6 +185,10 @@ async def fill_receive_event_properties( if activity.speak and activity.speak.strip(): properties[TelemetryConstants.SPEAK_PROPERTY] = activity.speak + TelemetryLoggerMiddleware.__populate_additional_channel_properties( + activity, properties + ) + # Additional properties can override "stock" properties if additional_properties: for prop in additional_properties: @@ -288,3 +294,25 @@ async def fill_delete_event_properties( properties[prop.key] = prop.value return properties + + @staticmethod + def __populate_additional_channel_properties( + activity: Activity, properties: dict, + ): + if activity.channel_id == Channels.ms_teams: + teams_channel_data: TeamsChannelData = activity.channel_data + + properties["TeamsTenantId"] = ( + teams_channel_data.tenant + if teams_channel_data and teams_channel_data.tenant + else "" + ) + + properties["TeamsUserAadObjectId"] = ( + activity.from_property.aad_object_id if activity.from_property else "" + ) + + if teams_channel_data and teams_channel_data.team: + properties["TeamsTeamInfo"] = TeamInfo.serialize( + teams_channel_data.team + )
diff --git a/libraries/botbuilder-core/tests/test_telemetry_middleware.py b/libraries/botbuilder-core/tests/test_telemetry_middleware.py --- a/libraries/botbuilder-core/tests/test_telemetry_middleware.py +++ b/libraries/botbuilder-core/tests/test_telemetry_middleware.py @@ -7,11 +7,14 @@ from typing import Dict from unittest.mock import Mock import aiounittest +from botframework.connector import Channels + from botbuilder.core import ( NullTelemetryClient, TelemetryLoggerMiddleware, TelemetryLoggerConstants, TurnContext, + MessageFactory, ) from botbuilder.core.adapters import TestAdapter, TestFlow from botbuilder.schema import ( @@ -19,7 +22,9 @@ ActivityTypes, ChannelAccount, ConversationAccount, + ConversationReference, ) +from botbuilder.schema.teams import TeamInfo, TeamsChannelData, TenantInfo class TestTelemetryMiddleware(aiounittest.AsyncTestCase): @@ -228,6 +233,47 @@ async def process(context: TurnContext) -> None: ] self.assert_telemetry_calls(telemetry, telemetry_call_expected) + async def test_log_teams(self): + telemetry = Mock() + my_logger = TelemetryLoggerMiddleware(telemetry, True) + + adapter = TestAdapter( + template_or_conversation=ConversationReference(channel_id=Channels.ms_teams) + ) + adapter.use(my_logger) + + team_info = TeamInfo(id="teamId", name="teamName",) + + channel_data = TeamsChannelData( + team=team_info, tenant=TenantInfo(id="tenantId"), + ) + + activity = MessageFactory.text("test") + activity.channel_data = channel_data + activity.from_property = ChannelAccount( + id="userId", name="userName", aad_object_id="aaId", + ) + + test_flow = TestFlow(None, adapter) + await test_flow.send(activity) + + telemetry_call_expected = [ + ( + TelemetryLoggerConstants.BOT_MSG_RECEIVE_EVENT, + { + "text": "test", + "fromId": "userId", + "recipientId": "bot", + "recipientName": "Bot", + "TeamsTenantId": TenantInfo(id="tenantId"), + "TeamsUserAadObjectId": "aaId", + "TeamsTeamInfo": TeamInfo.serialize(team_info), + }, + ), + ] + + self.assert_telemetry_calls(telemetry, telemetry_call_expected) + def create_reply(self, activity, text, locale=None): return Activity( type=ActivityTypes.message,
[PORT] Add Teams specific telemetry properties > Port this change from botbuilder-dotnet/master branch: https://github.com/microsoft/botbuilder-dotnet/pull/4256 Add Teams specific telemetry properties when activity received via the Teams channel. See also https://github.com/microsoft/botframework-sdk/issues/5855 # Changed projects * Microsoft.Bot.Builder * Microsoft.Bot.Builder.Tests
2020-07-14T15:07:39
microsoft/botbuilder-python
1,272
microsoft__botbuilder-python-1272
[ "1262" ]
ecaa4ede92c5fd9ccd8c0e94d4abe0ec822d1c76
diff --git a/libraries/botbuilder-core/botbuilder/core/activity_handler.py b/libraries/botbuilder-core/botbuilder/core/activity_handler.py --- a/libraries/botbuilder-core/botbuilder/core/activity_handler.py +++ b/libraries/botbuilder-core/botbuilder/core/activity_handler.py @@ -86,6 +86,8 @@ async def on_turn(self, turn_context: TurnContext): await self.on_end_of_conversation_activity(turn_context) elif turn_context.activity.type == ActivityTypes.typing: await self.on_typing_activity(turn_context) + elif turn_context.activity.type == ActivityTypes.installation_update: + await self.on_installation_update(turn_context) else: await self.on_unrecognized_activity_type(turn_context) @@ -365,6 +367,19 @@ async def on_typing_activity( # pylint: disable=unused-argument """ return + async def on_installation_update( # pylint: disable=unused-argument + self, turn_context: TurnContext + ): + """ + Override this in a derived class to provide logic specific to + ActivityTypes.InstallationUpdate activities. + + :param turn_context: The context object for this turn + :type turn_context: :class:`botbuilder.core.TurnContext` + :returns: A task that represents the work queued to execute + """ + return + async def on_unrecognized_activity_type( # pylint: disable=unused-argument self, turn_context: TurnContext ):
diff --git a/libraries/botbuilder-core/tests/test_activity_handler.py b/libraries/botbuilder-core/tests/test_activity_handler.py --- a/libraries/botbuilder-core/tests/test_activity_handler.py +++ b/libraries/botbuilder-core/tests/test_activity_handler.py @@ -73,6 +73,10 @@ async def on_typing_activity(self, turn_context: TurnContext): self.record.append("on_typing_activity") return await super().on_typing_activity(turn_context) + async def on_installation_update(self, turn_context: TurnContext): + self.record.append("on_installation_update") + return await super().on_installation_update(turn_context) + async def on_unrecognized_activity_type(self, turn_context: TurnContext): self.record.append("on_unrecognized_activity_type") return await super().on_unrecognized_activity_type(turn_context) @@ -229,6 +233,19 @@ async def test_typing_activity(self): assert len(bot.record) == 1 assert bot.record[0] == "on_typing_activity" + async def test_on_installation_update(self): + activity = Activity(type=ActivityTypes.installation_update) + + adapter = TestInvokeAdapter() + turn_context = TurnContext(adapter, activity) + + # Act + bot = TestingActivityHandler() + await bot.on_turn(turn_context) + + assert len(bot.record) == 1 + assert bot.record[0] == "on_installation_update" + async def test_healthcheck(self): activity = Activity(type=ActivityTypes.invoke, name="healthcheck",)
Add InstallationUpdate to ActivityHandler See parent issue: https://github.com/microsoft/botframework-sdk/issues/5959 [enhancement]
2020-07-23T13:48:18
microsoft/botbuilder-python
1,274
microsoft__botbuilder-python-1274
[ "1269" ]
09c95fc22ac324c0e489de96a163350978249499
diff --git a/libraries/botbuilder-schema/botbuilder/schema/__init__.py b/libraries/botbuilder-schema/botbuilder/schema/__init__.py --- a/libraries/botbuilder-schema/botbuilder/schema/__init__.py +++ b/libraries/botbuilder-schema/botbuilder/schema/__init__.py @@ -70,6 +70,7 @@ from .callerid_constants import CallerIdConstants from .health_results import HealthResults from .healthcheck_response import HealthCheckResponse +from .speech_constants import SpeechConstants __all__ = [ "Activity", @@ -139,4 +140,5 @@ "CallerIdConstants", "HealthResults", "HealthCheckResponse", + "SpeechConstants", ] diff --git a/libraries/botbuilder-schema/botbuilder/schema/speech_constants.py b/libraries/botbuilder-schema/botbuilder/schema/speech_constants.py new file mode 100644 --- /dev/null +++ b/libraries/botbuilder-schema/botbuilder/schema/speech_constants.py @@ -0,0 +1,14 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + + +class SpeechConstants: + """ + Defines constants that can be used in the processing of speech interactions. + """ + + EMPTY_SPEAK_TAG = '<speak version="1.0" xmlns="https://www.w3.org/2001/10/synthesis" xml:lang="en-US" />' + """ + The xml tag structure to indicate an empty speak tag, to be used in the 'speak' property of an Activity. + When set this indicates to the channel that speech should not be generated. + """
Add a constant for "empty speak tag" We have agreed on a xml tag structure to indicate an empty speak tag. The format of that tag is: ```xml <speak version="1.0" xmlns="https://www.w3.org/2001/10/synthesis" xml:lang="en-US" /> ``` Let's expose this string as a constant in the speech namespace. For internal user, you can get additional data here: microsoft/botframework-obi#85 Relates to: https://github.com/microsoft/botbuilder-dotnet/issues/4311 [enhancement]
2020-07-23T18:57:53
microsoft/botbuilder-python
1,303
microsoft__botbuilder-python-1303
[ "1302" ]
c17f030bac04841b6e9cd0dd5d035290b12391e0
diff --git a/libraries/botbuilder-azure/setup.py b/libraries/botbuilder-azure/setup.py --- a/libraries/botbuilder-azure/setup.py +++ b/libraries/botbuilder-azure/setup.py @@ -5,7 +5,7 @@ from setuptools import setup REQUIRES = [ - "azure-cosmos==3.1.2", + "azure-cosmos==3.2.0", "azure-storage-blob==2.1.0", "botbuilder-schema==4.10.0", "botframework-connector==4.10.0",
Bump azure-cosmos to v3.2.0 **Is your feature request related to a problem? Please describe.** We're currently on `azure-cosmos` v3.1.2. Not a ton of changes in 3.2.0, but it looks like it will be their last stable version, now that they're working on v4: ![image](https://user-images.githubusercontent.com/40401643/89065922-64fe7280-d321-11ea-8e3d-553ec1efbec4.png) **Additional context** Need to ensure all Cosmos tests are run live before merging (they're skipped by default). [enhancement]
2020-07-31T21:31:09