Example #1
0
    def testCaseAPIResultJSON(self):
        try:
            case = CommCareCase()
            # because of how setattr is overridden you have to set it to None in this wacky way
            case._doc['type'] = None
            case.save()
            self.assertEqual(None, CommCareCase.get(case._id).type)
            res_sanitized = CaseAPIResult(id=case._id, couch_doc=case, sanitize=True)
            res_unsanitized = CaseAPIResult(id=case._id, couch_doc=case, sanitize=False)

            json = res_sanitized.case_json
            self.assertEqual(json['properties']['case_type'], '')

            json = res_unsanitized.case_json
            self.assertEqual(json['properties']['case_type'], None)
Example #2
0
def get_cases(request, domain):
    request_params = request.GET

    if request.couch_user.is_commcare_user():
        user_id = request.couch_user.get_id
    else:
        user_id = request_params.get("user_id", "")

    if not user_id and not request.couch_user.is_web_user():
        return HttpResponseBadRequest("Must specify user_id!")

    ids_only = string_to_boolean(request_params.get("ids_only", "false"))
    case_id = request_params.get("case_id", "")
    footprint = string_to_boolean(request_params.get("footprint", "false"))
    accessor = CaseAccessors(domain)

    if toggles.HSPH_HACK.enabled(domain):
        hsph_case_id = request_params.get('hsph_hack', None)
        if hsph_case_id != 'None' and hsph_case_id and user_id:
            case = accessor.get_case(hsph_case_id)
            usercase_id = CommCareUser.get_by_user_id(
                user_id).get_usercase_id()
            usercase = accessor.get_case(usercase_id) if usercase_id else None
            return json_response(
                map(
                    lambda case: CaseAPIResult(
                        id=case['_id'], couch_doc=case, id_only=ids_only),
                    filter(None, [case, case.parent, usercase])))
Example #3
0
def get_cases(request, domain):

    if request.couch_user.is_commcare_user():
        user_id = request.couch_user.get_id
    else:
        user_id = request.REQUEST.get("user_id", "")

    if not user_id and not request.couch_user.is_web_user():
        return HttpResponseBadRequest("Must specify user_id!")

    ids_only = string_to_boolean(request.REQUEST.get("ids_only", "false"))
    case_id = request.REQUEST.get("case_id", "")
    footprint = string_to_boolean(request.REQUEST.get("footprint", "false"))
    include_children = string_to_boolean(
        request.REQUEST.get("include_children", "false"))
    if case_id and not footprint and not include_children:
        # short circuit everything else and just return the case
        # NOTE: this allows any user in the domain to access any case given
        # they know its ID, which is slightly different from the previous
        # behavior (can only access things you own + footprint). If we want to
        # change this contract we would need to update this to check the
        # owned case list + footprint
        case = CommCareCase.get(case_id)
        assert case.domain == domain
        cases = [CaseAPIResult(id=case_id, couch_doc=case, id_only=ids_only)]
Example #4
0
class CaseAPIMiscTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super(CaseAPIMiscTests, cls).setUpClass()
        cls.domain = uuid.uuid4().hex
        cls.project = create_domain(cls.domain)
        cls.username = uuid.uuid4().hex
        cls.password = "******"

        cls.user = CommCareUser.create(
            cls.domain, format_username(cls.username, cls.domain),
            cls.password)

    @classmethod
    def tearDownClass(cls):
        cls.user.delete()
        FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain)
        cls.project.delete()
        super(CaseAPIMiscTests, cls).tearDownClass()

    def testCaseAPIResultJSON(self):
        case = CommCareCase()
        # because of how setattr is overridden you have to set it to None in this wacky way
        case._doc['type'] = None
        case.save()
        self.addCleanup(case.delete)
        self.assertEqual(None, CommCareCase.get(case.case_id).type)
        res_sanitized = CaseAPIResult(domain=TEST_DOMAIN,
                                      id=case.case_id,
                                      couch_doc=case,
                                      sanitize=True)
        res_unsanitized = CaseAPIResult(domain=TEST_DOMAIN,
                                        id=case.case_id,
                                        couch_doc=case,
                                        sanitize=False)

        json = res_sanitized.case_json
        self.assertEqual(json['properties']['case_type'], '')

        json = res_unsanitized.case_json
        self.assertEqual(json['properties']['case_type'], None)
Example #5
0
            return json_response(
                map(
                    lambda case: CaseAPIResult(
                        id=case['_id'], couch_doc=case, id_only=ids_only),
                    filter(None, [case, case.parent, usercase])))

    if case_id and not footprint:
        # short circuit everything else and just return the case
        # NOTE: this allows any user in the domain to access any case given
        # they know its ID, which is slightly different from the previous
        # behavior (can only access things you own + footprint). If we want to
        # change this contract we would need to update this to check the
        # owned case list + footprint
        case = accessor.get_case(case_id)
        assert case.domain == domain
        cases = [CaseAPIResult(id=case_id, couch_doc=case, id_only=ids_only)]
    else:
        filters = get_filters_from_request_params(request_params)
        status = api_closed_to_status(request_params.get('closed', 'false'))
        case_type = filters.get('properties/case_type', None)
        cases = get_filtered_cases(domain,
                                   status=status,
                                   case_type=case_type,
                                   user_id=user_id,
                                   filters=filters,
                                   footprint=footprint,
                                   ids_only=ids_only,
                                   strip_history=True)
    return json_response(cases)

Example #6
0
                                               couch_doc=case,
                                               id_only=ids_only),
                    filter(None, [case, case.parent, usercase])))

    if case_id and not footprint:
        # short circuit everything else and just return the case
        # NOTE: this allows any user in the domain to access any case given
        # they know its ID, which is slightly different from the previous
        # behavior (can only access things you own + footprint). If we want to
        # change this contract we would need to update this to check the
        # owned case list + footprint
        case = accessor.get_case(case_id)
        assert case.domain == domain
        cases = [
            CaseAPIResult(domain=domain,
                          id=case_id,
                          couch_doc=case,
                          id_only=ids_only)
        ]
    else:
        filters = get_filters_from_request_params(request_params)
        status = api_closed_to_status(request_params.get('closed', 'false'))
        case_type = filters.get('properties/case_type', None)
        cases = get_filtered_cases(domain,
                                   status=status,
                                   case_type=case_type,
                                   user_id=user_id,
                                   filters=filters,
                                   footprint=footprint,
                                   ids_only=ids_only,
                                   strip_history=True)
    return json_response(cases)
Example #7
0
class CaseAPITest(TestCase):
    """
    Tests some of the Case API functions
    """
    domain = TEST_DOMAIN
    case_types = ['t1', 't2']
    user_ids = ['TEST_API1', 'TEST_API2']

    @classmethod
    def setUpClass(cls):
        super(CaseAPITest, cls).setUpClass()
        create_domain(cls.domain)
        cls.password = "******"

        def create_user(username):
            return CommCareUser.create(cls.domain,
                                       format_username(username, cls.domain),
                                       cls.password)

        cls.users = [create_user(id) for id in cls.user_ids]

        update_toggle_cache(toggles.CLOUDCARE_CACHE.slug, TEST_DOMAIN, True,
                            toggles.NAMESPACE_DOMAIN)

    @classmethod
    def tearDownClass(cls):
        for user in cls.users:
            django_user = user.get_django_user()
            django_user.delete()
            user.delete()
        clear_toggle_cache(toggles.CLOUDCARE_CACHE.slug, TEST_DOMAIN,
                           toggles.NAMESPACE_DOMAIN)
        super(CaseAPITest, cls).tearDownClass()

    def setUp(self):
        super(CaseAPITest, self).setUp()

        def create_case_set(user, child_user):
            # for each user we need one open and one closed case of
            # two different types.
            for type in self.case_types:
                c1 = _create_case(user, type, close=False)  # open
                _create_case(user, type, close=True)  # closed
                # child
                _create_case(child_user,
                             _child_case_type(type),
                             close=False,
                             index={'parent': ('parent-case', c1.case_id)})

        for i, user in enumerate(self.users):
            create_case_set(user, self.users[(i + 1) % len(self.users)])

        self.test_type = self.case_types[0]
        self.test_user_id = self.users[0]._id

    def tearDown(self):
        FormProcessorTestUtils.delete_all_cases_forms_ledgers(TEST_DOMAIN)
        super(CaseAPITest, self).tearDown()

    def assertListMatches(self, list, function):
        for item in list:
            self.assertTrue(function(item))

    @property
    def expectedOpenByType(self):
        return len(self.user_ids)

    @property
    def expectedClosedByType(self):
        return len(self.user_ids)

    @property
    def expectedByType(self):
        return self.expectedOpenByType + self.expectedClosedByType

    @property
    def expectedOpenByUser(self):
        return len(self.case_types) * 2  # one per type and child type

    @property
    def expectedClosedByUser(self):
        return len(self.case_types)

    @property
    def expectedByUser(self):
        return self.expectedOpenByUser + self.expectedClosedByUser

    @property
    def expectedOpenByUserWithFootprint(self):
        # each user gets 1 additional child case belonging to their cases
        # for each case type
        return self.expectedOpenByUser + len(self.case_types)

    @property
    def expectedClosedByUserWithFootprint(self):
        # each user gets 1 additional child case belonging to their cases
        return self.expectedClosedByUser

    @property
    def expectedOpen(self):
        return self.expectedOpenByUser * len(self.user_ids)

    @property
    def expectedClosed(self):
        return self.expectedClosedByUser * len(self.user_ids)

    @property
    def expectedAll(self):
        return len(self.user_ids) * len(self.case_types) * 3

    @run_with_all_backends
    def testGetAllOpen(self):
        list = get_filtered_cases(self.domain, status=CASE_STATUS_OPEN)
        self.assertEqual(self.expectedOpen, len(list))
        self.assertListMatches(list, lambda c: not c['closed'])

    @run_with_all_backends
    def testGetAllWithClosed(self):
        list = get_filtered_cases(self.domain, status=CASE_STATUS_ALL)
        self.assertEqual(self.expectedOpen + self.expectedClosed, len(list))

    @run_with_all_backends
    def testGetAllOpenWithType(self):
        list = get_filtered_cases(self.domain,
                                  status=CASE_STATUS_OPEN,
                                  case_type=self.test_type)
        self.assertEqual(self.expectedOpenByType, len(list))
        self.assertListMatches(
            list, lambda c: not c['closed'] and c['properties']['case_type'] ==
            self.test_type)

    @run_with_all_backends
    def testGetAllWithClosedAndType(self):
        list = get_filtered_cases(self.domain,
                                  status=CASE_STATUS_ALL,
                                  case_type=self.test_type)
        self.assertEqual(self.expectedByType, len(list))
        self.assertListMatches(
            list, lambda c: c['properties']['case_type'] == self.test_type)

    @run_with_all_backends
    def testGetOwnedOpen(self):
        list = get_filtered_cases(self.domain,
                                  user_id=self.test_user_id,
                                  status=CASE_STATUS_OPEN,
                                  footprint=False)
        self.assertEqual(self.expectedOpenByUser, len(list))
        self.assertListMatches(
            list,
            lambda c: not c['closed'] and c['user_id'] == self.test_user_id)

    @run_with_all_backends
    def testGetOwnedClosed(self):
        list = get_filtered_cases(self.domain,
                                  user_id=self.test_user_id,
                                  status=CASE_STATUS_CLOSED,
                                  footprint=False)
        self.assertEqual(self.expectedClosedByUser, len(list))
        self.assertListMatches(
            list, lambda c: c['closed'] and c['user_id'] == self.test_user_id)

    @run_with_all_backends
    def testGetOwnedBoth(self):
        list = get_filtered_cases(self.domain,
                                  user_id=self.test_user_id,
                                  status=CASE_STATUS_ALL,
                                  footprint=False)
        self.assertEqual(self.expectedByUser, len(list))
        self.assertListMatches(list,
                               lambda c: c['user_id'] == self.test_user_id)

    @run_with_all_backends
    def testGetOwnedOpenWithFootprint(self):
        list = get_filtered_cases(self.domain,
                                  user_id=self.test_user_id,
                                  status=CASE_STATUS_OPEN,
                                  footprint=True)
        self.assertEqual(self.expectedOpenByUserWithFootprint, len(list))
        self.assertListMatches(
            list,
            lambda c: not c['closed'] or c['user_id'] != self.test_user_id)

    @run_with_all_backends
    def testGetOwnedClosedWithFootprint(self):
        list = get_filtered_cases(self.domain,
                                  user_id=self.test_user_id,
                                  status=CASE_STATUS_CLOSED,
                                  footprint=True)
        self.assertEqual(self.expectedClosedByUserWithFootprint, len(list))
        self.assertListMatches(
            list, lambda c: c['closed'] or c['user_id'] != self.test_user_id)

    @run_with_all_backends
    def testGetOwnedBothWithFootprint(self):
        list = get_filtered_cases(self.domain,
                                  user_id=self.test_user_id,
                                  status=CASE_STATUS_ALL,
                                  footprint=True)
        self.assertEqual(
            self.expectedOpenByUserWithFootprint +
            self.expectedClosedByUserWithFootprint, len(list))
        # I don't think we can say anything super useful about this base set

    def testGetAllStripHistory(self):
        # strip history doesn't work on SQL domains
        list = get_filtered_cases(self.domain,
                                  status=CASE_STATUS_ALL,
                                  footprint=True,
                                  strip_history=True)
        self.assertEqual(self.expectedAll, len(list))
        self.assertListMatches(list, lambda c: len(c._couch_doc.actions) == 0)
        self.assertListMatches(list,
                               lambda c: len(c._couch_doc.xform_ids) == 0)

    @run_with_all_backends
    def testGetAllIdsOnly(self):
        list = get_filtered_cases(self.domain,
                                  status=CASE_STATUS_ALL,
                                  footprint=True,
                                  ids_only=True)
        self.assertEqual(self.expectedAll, len(list))
        self.assertListMatches(list, lambda c: c._couch_doc is None)
        self.assertListMatches(list,
                               lambda c: isinstance(c.to_json(), basestring))

    @run_with_all_backends
    def testFiltersOnAll(self):
        list = get_filtered_cases(
            self.domain,
            status=CASE_STATUS_ALL,
            filters={"properties/case_name": _type_to_name(self.test_type)})
        self.assertEqual(self.expectedByType, len(list))
        self.assertListMatches(
            list, lambda c: c['properties']['case_name'] == _type_to_name(
                self.test_type))

    @run_with_all_backends
    def testFiltersOnOwned(self):
        list = get_filtered_cases(
            self.domain,
            user_id=self.test_user_id,
            status=CASE_STATUS_ALL,
            filters={"properties/case_name": _type_to_name(self.test_type)})
        self.assertEqual(2, len(list))
        self.assertListMatches(
            list, lambda c: c['properties']['case_name'] == _type_to_name(
                self.test_type))

    @run_with_all_backends
    def testFiltersWithoutFootprint(self):
        name = _type_to_name(_child_case_type(self.test_type))
        list = get_filtered_cases(self.domain,
                                  user_id=self.test_user_id,
                                  status=CASE_STATUS_ALL,
                                  footprint=False,
                                  filters={"properties/case_name": name})
        self.assertEqual(1, len(list))
        self.assertListMatches(list,
                               lambda c: c['properties']['case_name'] == name)

    @run_with_all_backends
    def testFiltersWithFootprint(self):
        name = _type_to_name(_child_case_type(self.test_type))
        list = get_filtered_cases(self.domain,
                                  user_id=self.test_user_id,
                                  status=CASE_STATUS_ALL,
                                  footprint=True,
                                  filters={"properties/case_name": name})
        # when filtering with footprint, the filters get intentionally ignored
        # so just ensure the whole footprint including open and closed is available
        self.assertEqual(
            self.expectedOpenByUserWithFootprint +
            self.expectedClosedByUserWithFootprint, len(list))

    def testCaseAPIResultJSON(self):
        case = CommCareCase()
        # because of how setattr is overridden you have to set it to None in this wacky way
        case._doc['type'] = None
        case.save()
        self.addCleanup(case.delete)
        self.assertEqual(None, CommCareCase.get(case.case_id).type)
        res_sanitized = CaseAPIResult(domain=TEST_DOMAIN,
                                      id=case.case_id,
                                      couch_doc=case,
                                      sanitize=True)
        res_unsanitized = CaseAPIResult(domain=TEST_DOMAIN,
                                        id=case.case_id,
                                        couch_doc=case,
                                        sanitize=False)

        json = res_sanitized.case_json
        self.assertEqual(json['properties']['case_type'], '')

        json = res_unsanitized.case_json
        self.assertEqual(json['properties']['case_type'], None)