Пример #1
0
    def test_filter_by_user(self):
        """The filter_by_user() method returns the first UserSocialAuth object for member."""
        # A UserSocialAuth object for the self.member and the Resource
        self_member_result = UserSocialAuthFactory(user=self.member,
                                                   uid=self.member.id,
                                                   provider=Resource.name)
        # A UserSocialAuth object for the self.member, but for a different Resource
        UserSocialAuthFactory(user=self.member,
                              uid=self.member.id,
                              provider='other_resource')
        # A UserSocialAuth object for the Resource, but for a different member
        other_member = UserFactory()
        other_member_result = UserSocialAuthFactory(user=other_member,
                                                    uid=other_member.id,
                                                    provider=Resource.name)

        resource = Resource(self.member)
        # Calling the filter_by_user() method filters the UserSocialAuth
        # objects for the appropriate member, even if it's not the member
        # that the Resource was instantiated for.
        self.assertEqual(
            set(
                resource.filter_by_user(self.member).values_list('id',
                                                                 flat=True)),
            set([self_member_result.id]),
        )
        self.assertEqual(
            set(
                resource.filter_by_user(other_member).values_list('id',
                                                                  flat=True)),
            set([other_member_result.id]),
        )
Пример #2
0
    def test_init(self):
        """Initializing a Resource sets the member and db_object."""
        with self.subTest('Initializing Resource requires a member'):
            with self.assertRaises(TypeError):
                Resource()

        with self.subTest('Initializing Resource sets member and db_object'):
            # A UserSocialAuth object for the self.member and the Resource
            user_social_auth = UserSocialAuthFactory(user=self.member,
                                                     uid=self.member.id,
                                                     provider=Resource.name)
            # A UserSocialAuth object for the self.member, but for a different Resource
            UserSocialAuthFactory(user=self.member,
                                  uid=self.member.id,
                                  provider='other_resource')
            # A UserSocialAuth object for the Resource, but for a different member
            other_member = UserFactory()
            UserSocialAuthFactory(user=other_member,
                                  uid=other_member.id,
                                  provider=Resource.name)

            # Initializing the Resource sets the user_social_auth (for the
            # self.member and the Resource) as the db_object.
            resource = Resource(self.member)
            self.assertEqual(resource.member, self.member)
            self.assertEqual(resource.db_object, user_social_auth)
Пример #3
0
    def test_get(self):
        """Calling the .get() method makes a request to get the member's data."""
        # The member has received an access_token to get their own data.
        access_token = 'accessTOKENhere'
        refresh_token = 'refreshTOKEN'
        UserSocialAuthFactory(user=self.member,
                              uid=self.member.id,
                              provider=Resource.name,
                              extra_data={
                                  'refresh_token': refresh_token,
                                  'access_token': access_token
                              })
        resource = Resource(self.member)
        requested_record_type = 'prescriptions'

        # GET the data for the member.
        # Note: we mock the use of the requests library, so we don't make requests
        # from within the test.
        with HTTMock(self.response_content_success):
            data = resource.get(requested_record_type)

        # The response matches the self.response_content_success
        self.assertEqual(data.status_code,
                         self.expected_response_success['status_code'])
        self.assertEqual(data.json(),
                         self.expected_response_success['content'])
        # The request was made to a URL built from the Resource's url_for_data,
        # and the requested_record_type.
        expected_url = Resource.url_for_data.format(
            record_type=requested_record_type)
        self.assertEqual(data.request.url, expected_url)
        # The request was made with a 'Bearer' Authorization header that includes
        # the access_token.
        self.assertEqual(data.request.headers['Authorization'],
                         'Bearer {}'.format(access_token))
Пример #4
0
    def give_user_access_to_member_token(self, user, member, provider_name):
        """
        Give the user access to the member's access_token, and return access_token.

        This method creates necessary database objects so that the user is in an
        Organization that has a ResourceGrant for the member's Resource, so the
        user can use the member's access_token to get data about the member.
        """
        # The user is a part of an Organization
        organization = OrganizationFactory()
        organization.agents.add(user)
        # The member has received an access_token to get their own data.
        provider_name = provider_name
        access_token = 'accessTOKENhere'
        UserSocialAuthFactory(
            user=member,
            provider=provider_name,
            extra_data={'refresh_token': 'refreshTOKEN', 'access_token': access_token},
        )
        # The member has approved the Organization's request for the member's data
        resource_request = ResourceRequestFactory(
            member=member,
            organization=organization,
            resourcegrant=None,
            status=REQUEST_APPROVED,
        )
        ResourceGrantFactory(
            member=resource_request.member,
            organization=resource_request.organization,
            resource_class_path=resource_request.resource_class_path,
            resource_request=resource_request,
        )
Пример #5
0
    def test_get_permissions(self):
        """
        A user may see a member's data sources, if:
          - the request.user is the member, or
          - the request.user is in an Organization that has an approved
            ResourceRequest for the member's data
        """
        # Create a member
        member = UserFactory()
        # The member has received an access_token to get their own data.
        provider_name = Resource.name
        access_token = 'accessTOKENhere'
        UserSocialAuthFactory(
            user=member,
            provider=provider_name,
            extra_data={
                'refresh_token': 'refreshTOKEN',
                'access_token': access_token
            },
        )

        # The URLs that will be used in this test
        member_data_url = reverse(self.url_name, kwargs={'pk': member.pk})

        with self.subTest(
                "A member's data sources without an approved ResourceRequest"):

            # We mock the use of the requests library, so we don't make real
            # requests from within the test.
            with HTTMock(self.response_content_success):
                response = self.client.get(member_data_url)

            # The request.user does not have access to the member's data
            self.assertEqual(response.status_code, 302)

        with self.subTest(
                "A member's data sources with an approved ResourceRequest, other Organization"
        ):
            # The member has approved some Organization's request for the member's data
            organization = OrganizationFactory()
            resource_request = ResourceRequestFactory(
                member=member,
                organization=organization,
                resourcegrant=None,
                status=REQUEST_APPROVED,
            )
            resource_grant = ResourceGrantFactory(
                member=resource_request.member,
                organization=resource_request.organization,
                resource_class_path=resource_request.resource_class_path,
                resource_request=resource_request,
            )

            # We mock the use of the requests library, so we don't make real
            # requests from within the test.
            with HTTMock(self.response_content_success):
                response = self.client.get(member_data_url)

            # The request.user now has access to the member's data
            self.assertEqual(response.status_code, 302)

        with self.subTest(
                "A member's data sources with approved ResourceRequest from request.user's Organization"
        ):
            # The request.user is now in the organization
            organization.agents.add(self.user)

            # We mock the use of the requests library, so we don't make real
            # requests from within the test.
            with HTTMock(self.response_content_success):
                response = self.client.get(member_data_url)

            # The request.user does not have access to the member's data, since
            # the request.user is not in the organization.
            self.assertEqual(response.status_code, 200)

        with self.subTest('A member requesting their own data'):
            self.client.logout()
            self.client.force_login(member)

            # We mock the use of the requests library, so we don't make real
            # requests from within the test.
            with HTTMock(self.response_content_success):
                response = self.client.get(member_data_url)

            # The request.user has access to their own data, regardless of their
            # Organization.
            self.assertEqual(response.status_code, 200)

            # Even if we remove the ResourceRequest and ResourceGrant objects,
            # the member is allowed to see their own data.
            resource_request.delete()
            resource_grant.delete()
            with HTTMock(self.response_content_success):
                response = self.client.get(member_data_url)
            self.assertEqual(response.status_code, 200)
Пример #6
0
    def test_post(self):
        """POSTing to the user_settings view can update a user's picture URL."""
        with self.subTest('no data'):
            # Since POSTs with valid data use the requests library to make a request
            # to the settings.SOCIAL_AUTH_VMI_HOST URL, mock uses of the requests
            # library here.
            with HTTMock(self.response_content_success):
                response = self.client.post(self.url, {'picture': None})

            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.context['form'].errors,
                             {'picture': ['This field is required.']})
            # The self.user's UserProfile was not updated
            self.user.userprofile.refresh_from_db()
            self.assertEqual(self.user.userprofile.picture_url, '')
            # No requests were made to VMI
            self.assertEqual(self.response_content_success.call['count'], 0)

        with self.subTest('invalid data'):
            # Since POSTs with valid data use the requests library to make a request
            # to the settings.SOCIAL_AUTH_VMI_HOST URL, mock uses of the requests
            # library here.
            with HTTMock(self.response_content_success):
                response = self.client.post(self.url,
                                            {'picture': 'not a valid image'})

            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.context['form'].errors,
                             {'picture': ['This field is required.']})
            # The self.user's UserProfile was not updated
            self.user.userprofile.refresh_from_db()
            self.assertEqual(self.user.userprofile.picture_url, '')
            # No requests were made to VMI
            self.assertEqual(self.response_content_success.call['count'], 0)

        with self.subTest('valid data, no request.user UserSocialAuth object'):
            # If the request.user does not have a UserSocialAuth object for VMI,
            # then the response is an error.

            # Since POSTs with valid data use the requests library to make a request
            # to the settings.SOCIAL_AUTH_VMI_HOST URL, mock uses of the requests
            # library here.
            test_image = self.get_test_image_for_upload()
            with HTTMock(self.response_content_success):
                response = self.client.post(
                    self.url, {
                        'picture':
                        SimpleUploadedFile('picture.png',
                                           test_image.getvalue())
                    })

            self.assertEqual(response.status_code, 200)
            self.assertEqual(
                response.context['errors'], {
                    'user':
                    '******'.format(
                        settings.SOCIAL_AUTH_NAME)
                })

            # The self.user's UserProfile was not updated
            self.user.userprofile.refresh_from_db()
            self.assertEqual(self.user.userprofile.picture_url, '')
            # No requests were made to VMI
            self.assertEqual(self.response_content_success.call['count'], 0)

        with self.subTest(
                'valid data, request.user has a UserSocialAuth object'):
            # Create a UserSocialAuth object for the self.user for VMI
            UserSocialAuthFactory(
                user=self.user,
                provider=settings.SOCIAL_AUTH_NAME,
                extra_data={
                    'refresh_token': 'refreshTOKEN',
                    'access_token': 'accessTOKENhere'
                },
                uid=random.randint(100000000000000, 999999999999999),
            )

            test_image = self.get_test_image_for_upload()

            # Since POSTs with valid data use the requests library to make a request
            # to the settings.SOCIAL_AUTH_VMI_HOST URL, mock uses of the requests
            # library here.
            with HTTMock(self.response_content_success):
                response = self.client.post(
                    self.url, {
                        'picture':
                        SimpleUploadedFile('picture.png',
                                           test_image.getvalue())
                    })

            # A successful create redirects to the next page of the creation process.
            self.assertEqual(response.status_code, 200)
            # The self.user's UserProfile was updated
            self.user.userprofile.refresh_from_db()
            self.assertEqual(self.user.userprofile.picture_url,
                             self.vmi_picture_url)
            # One request was made to VMI
            self.assertEqual(self.response_content_success.call['count'], 1)