Exemplo n.º 1
0
    def test_post_invalid(self):
        """Invalid post conditions should results HTTP 422 Unprocessable entity
        * 'member' does not exist
        * 'organization' does not exist
        * 'status' is not in ['approve', 'deny', 'revoke']
        """
        request_url = reverse(self.url_name)
        with self.subTest(
                'post with non-existing member results in error message'):
            new_user = UserFactory()
            new_user_pk = new_user.pk
            new_user.delete()  # now we know they don't exist.
            response = self.client.post(
                request_url,
                {
                    'approve': 'Not gonna work',
                    'member': new_user_pk,
                    'organization': self.organizations[0].pk,
                },
            )
            self.assertEqual(response.status_code, 422)
            self.assertIn(b'member',
                          response.content)  # error with the member field

        with self.subTest(
                'post with non-existing organization results in error message'
        ):
            new_org = OrganizationFactory()
            new_org_pk = new_org.pk
            new_org.delete()  # now we know they don't exist.
            response = self.client.post(
                request_url,
                {
                    'approve': 'Not gonna work',
                    'member': self.user.pk,
                    'organization': new_org_pk,
                },
            )
            self.assertEqual(response.status_code, 422)
            self.assertIn(
                b'organization',
                response.content)  # error with the organization field

        with self.subTest('post with wrong status results in error message'):
            response = self.client.post(
                request_url,
                {
                    'member': self.user.pk,
                    'organization': self.organizations[0].pk
                },
            )
            self.assertEqual(response.status_code, 422)
            self.assertIn(b'status',
                          response.content)  # error with the status field
Exemplo n.º 2
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]),
        )
Exemplo n.º 3
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)
Exemplo n.º 4
0
    def test_get(self):
        """A successful request to get data for a member."""
        # Create a member
        member = UserFactory()
        # Give the self.user access to the member's access_token.
        provider_name = Resource.name
        self.give_self_user_access_to_member_token(member, provider_name)

        # A user at the Organization (the self.user) GETs the data for the member.
        url = reverse(
            self.url_name,
            kwargs={
                'pk': member.pk,
                'resource_name': provider_name,
                'record_type': 'prescriptions'
            }
        )
        # 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(url)

        # Here, we assert that the response has the expected mocked response.
        # More specific testing for the Resource.get() method exists in the
        # sharemyhealth app.
        self.assertEqual(response.status_code, 200)
        self.assertEqual(
            response.context['data'].json(),
            self.expected_response_success['content']
        )
        self.assertTemplateUsed(response, 'member/data.html')
Exemplo n.º 5
0
    def test_authenticated(self):
        """The user must be authenticated to see records."""
        # Create a member
        member = UserFactory()
        # Give the self.user access to the member's access_token.
        provider_name = Resource.name
        self.give_user_access_to_member_token(self.user, member, provider_name)
        url = reverse(self.url_name,
                      kwargs={
                          'pk': member.pk,
                          'resource_name': 'list'
                      })

        with self.subTest('Authenticated'):
            self.client.force_login(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(url)
            self.assertEqual(response.status_code, 200)

        with self.subTest('Not authenticated'):
            self.client.logout()
            response = self.client.get(url)
            expected_redirect = '{}?next={}'.format(reverse('login'), url)
            self.assertRedirects(response, expected_redirect)
Exemplo n.º 6
0
    def test_authenticated(self):
        """The user must be authenticated to get a member's data."""
        # Create a member
        member = UserFactory()
        # Give the self.user access to the member's access_token.
        provider_name = Resource.name
        self.give_self_user_access_to_member_token(member, provider_name)

        # The url that will be used during this test to try to get the member's data
        url = reverse(self.url_name,
                      kwargs={
                          'pk': member.pk,
                          'resource_name': provider_name,
                          'record_type': 'prescriptions'
                      })

        with self.subTest('Not authenticated'):
            self.client.logout()
            # 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(url)

            expected_redirect = '{}?next={}'.format(reverse('home'), url)
            self.assertRedirects(response, expected_redirect)

        with self.subTest('Authenticated'):
            self.client.force_login(self.user)
            # 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(url)

            self.assertEqual(response.status_code, 200)
Exemplo n.º 7
0
    def test_parameters(self):
        """Sending invalid parameters into the function returns a 404 response."""
        # Create a member
        member = UserFactory()
        # Give the self.user access to the member's access_token.
        provider_name = Resource.name
        self.give_self_user_access_to_member_token(member, provider_name)

        with self.subTest('invalid resource_name parameter'):
            url = reverse(self.url_name,
                          kwargs={
                              'pk': member.pk,
                              'resource_name': 'invalid_name',
                              'record_type': 'prescriptions'
                          })

            # 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(url)

            self.assertEqual(response.status_code, 404)

        with self.subTest('invalid record_type parameter'):
            url = reverse(self.url_name,
                          kwargs={
                              'pk': member.pk,
                              'resource_name': provider_name,
                              'record_type': 'invalid_name'
                          })

            # 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(url)

            self.assertEqual(response.status_code, 404)

        for valid_resource_name in settings.RESOURCE_NAME_AND_CLASS_MAPPING.keys(
        ):
            for valid_record_type in settings.VALID_MEMBER_DATA_RECORD_TYPES:
                with self.subTest(resource_name=valid_resource_name,
                                  record_type=valid_record_type):
                    url = reverse(self.url_name,
                                  kwargs={
                                      'pk': member.pk,
                                      'resource_name': valid_resource_name,
                                      'record_type': valid_record_type
                                  })

                    # 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(url)

                    self.assertEqual(response.status_code, 200)
Exemplo n.º 8
0
 def setUp(self):
     super().setUp()
     self.member = UserFactory()
     # When we mock uses of the requests library in this test class, this is
     # the expected mock response.
     self.expected_response_success = {
         'status_code': 200,
         'content': {
             'test_key': 'Test content'
         },
     }
Exemplo n.º 9
0
    def test_post_user_unauthorized(self):
        """posting dismissal of another user's notification raises 404"""
        other_user = UserFactory()
        notification = Notification.objects.create(
            notify=other_user, actor=self.user, message="Notify Other User"
        )
        pk = notification.pk

        response = self.client.post(reverse('notifications:dismiss', kwargs={'pk': pk}))

        self.assertEqual(response.status_code, 404)
Exemplo n.º 10
0
    def test_resource_grant_needed(self):
        """Requesting to GET the member's data without a ResourceGrant returns a 404 response."""
        # Create a member
        member = UserFactory()
        # Give the self.user access to the member's access_token. This creates a
        # ResourceGrant for the member's access_token to the request.user's Organization.
        provider_name = Resource.name
        self.give_self_user_access_to_member_token(member, provider_name)

        with self.subTest('with ResourceGrant'):
            url = reverse(
                self.url_name,
                kwargs={
                    'pk': member.pk,
                    'resource_name': provider_name,
                    'record_type': 'prescriptions'
                }
            )

            # 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(url)

            self.assertEqual(response.status_code, 200)

        with self.subTest('without ResourceGrant'):
            # Remove the ResourceGrant for the member's access_token to the
            # request.user's Organization.
            ResourceGrant.objects.filter(
                member=member,
                organization__users=self.user
            ).delete()

            url = reverse(
                self.url_name,
                kwargs={
                    'pk': member.pk,
                    'resource_name': provider_name,
                    'record_type': 'prescriptions'
                }
            )
            # 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(url)

            # Because the self.user's Organization no longer has a ResourceGrant
            # for the member's access_token, the response has a 404 status_code.
            self.assertEqual(response.status_code, 404)
Exemplo n.º 11
0
    def test_get(self):
        """The response context_data should include the notifications for request.user,
        but not the notifications created for another user.
        """
        for i in range(3):
            Notification.objects.create(notify=self.user, actor=self.user, message="Notify %d" % i)
        other_user = UserFactory()
        for i in range(1):
            Notification.objects.create(notify=other_user, actor=self.user, message="Notify %d" % i)

        response = self.client.get(reverse(self.url_name))

        self.assertEqual(response.status_code, 200)
        for notification in response.context_data['notifications']:
            self.assertEqual(notification.notify, self.user)
Exemplo n.º 12
0
    def test_get(self):
        """GET the data sources view."""
        # Create a member
        member = UserFactory()
        # Give the self.user access to the member's access_token.
        provider_name = Resource.name
        self.give_user_access_to_member_token(self.user, member, provider_name)

        url = reverse(self.url_name, kwargs={'pk': member.pk})

        # 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(url)

        self.assertEqual(response.status_code, 200)
Exemplo n.º 13
0
    def test_authenticated(self):
        """The user must be authenticated to see data sources."""
        # Create a member
        member = UserFactory()
        # Give the self.user access to the member's access_token.
        provider_name = Resource.name
        self.give_user_access_to_member_token(self.user, member, provider_name)
        url = reverse(self.url_name, kwargs={'pk': member.pk})

        with self.subTest('Authenticated'):
            self.client.force_login(self.user)
            response = self.client.get(url)
            self.assertEqual(response.status_code, 200)

        with self.subTest('Not authenticated'):
            self.client.logout()
            response = self.client.get(url)
            expected_redirect = '{}?next={}'.format(reverse('login'), url)
            self.assertRedirects(response, expected_redirect)
Exemplo n.º 14
0
    def test_context_data(self):
        """
        OUTDATED
        GETting records view puts response of get_member_data() into the context.
        """
        # Create a member
        member = UserFactory()
        # Give the self.user access to the member's access_token.
        provider_name = Resource.name
        self.give_user_access_to_member_token(self.user, member, provider_name)

        url = reverse(self.url_name, kwargs={'pk': member.pk, 'resource_name': 'list'})
        # 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(url)

        # The response has data matches the mocked response.
        self.assertEqual(response.status_code, 200)
Exemplo n.º 15
0
 def test_str(self):
     """Test for string representation."""
     user = UserFactory()
     self.assertEqual(str(user.username), user.username)
Exemplo n.º 16
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)