def _create_ledger(domain,
                   entry_id,
                   balance,
                   case_id=None,
                   section_id='stock'):
    user_id = 'user1'
    utcnow = datetime.utcnow()

    case_id = case_id or uuid.uuid4().hex
    case = CommCareCase(
        case_id=case_id,
        domain=domain,
        type='',
        owner_id=user_id,
        opened_on=utcnow,
        modified_on=utcnow,
        modified_by=user_id,
        server_modified_on=utcnow,
    )

    case.save(with_tracked_models=True)

    ledger = LedgerValue(domain=domain,
                         case_id=case_id,
                         section_id=section_id,
                         entry_id=entry_id,
                         balance=balance,
                         last_modified=utcnow)

    LedgerAccessorSQL.save_ledger_values([ledger])
    return ledger
Example #2
0
    def test_registration_response(self, json_response_mock, update_case_mock, payload_doc_mock,
                                   repeat_record_repeater_mock):
        case_id = uuid.uuid4().hex
        person_case_id = uuid.uuid4().hex
        case_json = {
            'person_case_id': person_case_id,
            'api': COWIN_API_DATA_REGISTRATION_IDENTIFIER
        }
        case = CommCareCase(domain=self.domain, type='cowin_api_data', case_id=case_id, case_json=case_json,
                            server_modified_on=datetime.datetime.utcnow())
        payload_doc_mock.return_value = case

        response_json = {
            "beneficiary_reference_id": "1234567890123",
            "isNewAccount": "Y"
        }

        response = requests.Response()
        response.status_code = 200
        json_response_mock.return_value = response_json

        repeat_record = RepeatRecord(payload_id=case_id)
        repeater = BeneficiaryRegistrationRepeater(domain=self.domain)
        repeat_record_repeater_mock.return_value = repeater

        repeater.handle_response(response, repeat_record)

        update_case_mock.assert_called_with(
            self.domain, person_case_id, case_properties={'cowin_beneficiary_reference_id': "1234567890123"},
            device_id='custom.cowin.repeaters.BeneficiaryRegistrationRepeater'
        )
Example #3
0
 def test_load_session_data_for_commconnect_case(self):
     user = CommCareCase(name='A case', case_id=uuid.uuid4().hex)
     data = get_user_contributions_to_touchforms_session(
         'cloudcare-tests', user)
     self.assertEqual('A case', data['username'])
     self.assertEqual(user.case_id, data['user_id'])
     self.assertEqual({}, data['user_data'])
Example #4
0
    def test_vaccination_response(self, update_case_mock, payload_doc_mock, repeat_record_repeater_mock):
        case_id = uuid.uuid4().hex
        person_case_id = uuid.uuid4().hex
        case_json = {
            'person_case_id': person_case_id,
            'api': COWIN_API_DATA_VACCINATION_IDENTIFIER,
            'dose': "1"
        }
        case = CommCareCase(domain=self.domain, type='cowin_api_data', case_id=case_id, case_json=case_json,
                            server_modified_on=datetime.datetime.utcnow())
        payload_doc_mock.return_value = case

        response = requests.Response()
        response.status_code = 204

        repeat_record = RepeatRecord(payload_id=case_id)
        repeater = BeneficiaryVaccinationRepeater(domain=self.domain)

        repeat_record_repeater_mock.return_value = repeater
        repeater.handle_response(response, repeat_record)

        update_case_mock.assert_called_with(
            self.domain, person_case_id, case_properties={'dose_1_notified': True},
            device_id='custom.cowin.repeaters.BeneficiaryVaccinationRepeater'
        )
    def setUpClass(cls):
        super().setUpClass()
        case_type = CaseType.objects.create(domain=DOMAIN, name='mother')
        cls.resource_type = FHIRResourceType.objects.create(
            domain=DOMAIN,
            case_type=case_type,
            name='Patient',
        )
        for name, jsonpath in [
            ('name', '$.name[0].text'),
            ('first_name', '$.name[0].given[0]'),
            ('honorific', '$.name[0].prefix[0]'),
            ('date_of_birth', '$.birthDate'),
        ]:
            prop = CaseProperty.objects.create(case_type=case_type, name=name)
            FHIRResourceProperty.objects.create(
                resource_type=cls.resource_type,
                case_property=prop,
                jsonpath=jsonpath,
            )

        cls.case_id = str(uuid4())
        cls.case = CommCareCase(case_id=cls.case_id,
                                domain=DOMAIN,
                                type='mother',
                                name='Mehter Plethwih',
                                case_json={
                                    'first_name': 'Plethwih',
                                    'honorific': 'Mehter',
                                    'date_of_birth': '1970-01-01',
                                    'children': ['Hewsos', 'the twins'],
                                })
Example #6
0
def mock_get_cases(self, case_ids, domain=None, ordered=False):
    return [{
        '65e55473-e83b-4d78-9dde-eaf949758997': CommCareCase(
            case_id='65e55473-e83b-4d78-9dde-eaf949758997',
            type='paciente',
            name='Elsa',
            case_json={'estado_tarv': '1', 'tb': '0'},
        )
    }[case_id] for case_id in case_ids]
Example #7
0
 def test_sets_index_with_doc_type(self):
     data = {
         'indices': [{
             'doc_type': 'CommCareCaseIndex',
             'referenced_id': 'some_id'
         }]
     }
     case = CommCareCase(**data)
     index = case.indices[0]
     self.assertEqual(index.referenced_id, 'some_id')
Example #8
0
    def test_casedb_already_has_cases(self):
        casedb_cache = FormProcessorInterface().casedb_cache
        case = CaseFactory().create_case()
        case_db = casedb_cache(initial=[
            CommCareCase(case_id='fake1'),
            CommCareCase(case_id='fake2'),
        ])
        form = XFormInstance.objects.get_form(case.xform_ids[0])
        received = []

        def receive_cases(sender, xform, cases, **kwargs):
            received.extend(cases)

        cases_received.connect(receive_cases)
        try:
            process_cases_with_casedb([form], case_db)
            self.assertEqual(len(received), 1)
        finally:
            cases_received.disconnect(receive_cases)
Example #9
0
 def setUp(self):
     self.case = CommCareCase(
         domain=DOMAIN,
         case_id="123456",
         type="person",
         name="Eric Idle",
         external_id="94d60c79-59b5-4a2c-90a5-325d6e32b3db",
         modified_on=datetime.utcnow(),
         server_modified_on=datetime.utcnow(),
     )
     self.case.save()
def create_commcare_case(data):
    cccsql = CommCareCase(
        case_id=data['case_id'],
        domain=data['domain'],
        type=data['type'],
        name=data['name'],
        owner_id=data['owner_id'],
        modified_by=data['modified_by'],
        modified_on=datetime.utcnow(),
        server_modified_on=datetime.utcnow(),
    )
    cccsql.save()
    return cccsql
Example #11
0
 def setUp(self):
     now = datetime.utcnow()
     self.case_id = str(uuid4())
     self.case = CommCareCase(
         case_id=self.case_id,
         domain=DOMAIN,
         type='person',
         name='Ted',
         owner_id=str(uuid4()),
         modified_on=now,
         server_modified_on=now,
     )
     self.case.save()
Example #12
0
def test_case_to_json():
    case_id = str(uuid4())
    case = CommCareCase(
        case_id=case_id,
        domain=DOMAIN,
        type='case',
        name='Justin Case',
        case_json={
            'given_name': 'Justin',
            'family_name': 'Case',
            'actions': 'eating sleeping typing',
            'indices': 'Dow_Jones_Industrial_Average S&P_500',
        },
    )
    case_dict = case.to_json()
    assert_equal(
        case_dict,
        {
            '_id': case_id,
            'actions': [],  # Not replaced by case_json
            'backend_id': 'sql',
            'case_attachments': {},
            'case_id': case_id,
            'case_json': {
                'actions': 'eating sleeping typing',
                'family_name': 'Case',
                'given_name': 'Justin',
                'indices': 'Dow_Jones_Industrial_Average S&P_500',
            },
            'closed': False,
            'closed_by': None,
            'closed_on': None,
            'deleted': False,
            'doc_type': 'CommCareCase',
            'domain': DOMAIN,
            'external_id': None,
            'family_name': 'Case',
            'given_name': 'Justin',
            'indices': [],  # Not replaced by case_json
            'location_id': None,
            'modified_by': '',
            'modified_on': None,
            'name': 'Justin Case',
            'opened_by': None,
            'opened_on': None,
            'owner_id': '',
            'server_modified_on': None,
            'type': 'case',
            'user_id': '',
            'xform_ids': [],
        })
Example #13
0
    def _create_change(self):
        now = datetime.utcnow()
        case = CommCareCase(
            case_id=uuid4().hex,
            domain=self.domain,
            modified_on=now,
            server_modified_on=now,
        )
        case.save()

        change = Change(case.case_id,
                        'seq',
                        document_store=CaseDocumentStore(self.domain))
        return change, case
Example #14
0
 def hard_rebuild_case(domain, case_id, detail, lock=True, save=True):
     assert save or not lock, "refusing to lock when not saving"
     if lock:
         # only record metric if locking since otherwise it has been
         # (most likley) recorded elsewhere
         case_load_counter("rebuild_case", domain)()
     case, lock_obj = FormProcessorSQL.get_case_with_lock(case_id,
                                                          lock=lock)
     found = bool(case)
     if not found:
         case = CommCareCase(case_id=case_id, domain=domain)
         if lock:
             lock_obj = CommCareCase.get_obj_lock_by_id(case_id)
             acquire_lock(lock_obj, degrade_gracefully=False)
Example #15
0
 def setUp(self):
     i1 = {
         'identifier': 'i1',
         'referenced_type': 't1',
         'referenced_id': 'id1',
     }
     i2 = {
         'identifier': 'i2',
         'referenced_type': 't2',
         'referenced_id': 'id2',
     }
     self.i1 = CommCareCaseIndex(**i1)
     self.i2 = CommCareCaseIndex(**i2)
     self.case = CommCareCase(indices=[i1, i2])
Example #16
0
    def test_get_case_types_caching(self):
        self._send_case_to_es(case_type='t1')

        self.assertEqual({'t1'}, get_case_types_for_domain_es(self.domain))

        self._send_case_to_es(case_type='t2')
        # cached response
        self.assertEqual({'t1'}, get_case_types_for_domain_es(self.domain))

        # simulate a save
        from corehq.form_processor.signals import sql_case_post_save
        sql_case_post_save.send(self,
                                case=CommCareCase(domain=self.domain,
                                                  type='t2'))

        self.assertEqual({'t1', 't2'},
                         get_case_types_for_domain_es(self.domain))
Example #17
0
def new_case(domain=DOMAIN,
             user_id=DEFAULT_USER,
             owner_id=DEFAULT_USER,
             type=DEFAULT_CASE_TYPE,
             name=DEFAULT_CASE_NAME,
             closed=False,
             **kwargs):
    kwargs.setdefault("case_id", uuid.uuid4().hex)
    kwargs.setdefault("modified_on", datetime.utcnow())
    kwargs.setdefault("server_modified_on", datetime.utcnow())
    return CommCareCase(domain=domain,
                        user_id=user_id,
                        owner_id=owner_id,
                        type=type,
                        name=name,
                        closed=closed,
                        **kwargs)
Example #18
0
def wrap_case_search_hit(hit, include_score=False, is_related_case=False):
    """Convert case search index hit to CommCareCase

    Nearly the opposite of
    `corehq.pillows.case_search.transform_case_for_elasticsearch`.

    The "case_properties" list of key/value pairs is converted to a dict
    and assigned to `case_json`. 'Secial' case properties are excluded
    from `case_json`, even if they were present in the original case's
    dynamic properties.

    All fields excluding "case_properties" and its contents are assigned
    as attributes on the case object if `CommCareCase` has a field
    with a matching name. Fields like "doc_type" and "@indexed_on" are
    ignored.

    Warning: `include_score=True` or `is_related_case=True` may cause
    the relevant user-defined properties to be overwritten.

    :returns: A `CommCareCase` instance.
    """
    from corehq.form_processor.models import CommCareCase
    data = hit.get("_source", hit)
    _SPECIAL_PROPERTIES = SPECIAL_CASE_PROPERTIES_MAP
    _VALUE = VALUE
    case = CommCareCase(
        case_id=data.get("_id", None),
        case_json={
            prop["key"]: prop[_VALUE]
            for prop in data.get(CASE_PROPERTIES_PATH, {})
            if prop["key"] not in _SPECIAL_PROPERTIES
        },
        indices=data.get("indices", []),
    )
    _CONVERSIONS = CONVERSIONS
    _setattr = setattr
    case_fields = _case_fields()
    for key, value in data.items():
        if key in case_fields:
            if value is not None and key in _CONVERSIONS:
                value = _CONVERSIONS[key](value)
            _setattr(case, key, value)
    if include_score:
        case.case_json[RELEVANCE_SCORE] = hit['_score']
Example #19
0
    def get_case(self, case_json=None):
        utcnow = datetime.utcnow()
        case_json = self.props if case_json is None else case_json
        intent_case = CommCareCase(
            domain=SOURCE_DOMAIN,
            type=self.CASE_TYPE,
            case_json=case_json,
            case_id=uuid.uuid4().hex,
            user_id="local_user1",
            opened_on=utcnow,
            modified_on=utcnow,
        )
        intent_case.track_create(CaseTransaction(form_id="form123", type=CaseTransaction.TYPE_FORM))

        def _mock_subcases(*args, **kwargs):
            return self.subcases

        intent_case.get_subcases = _mock_subcases
        return intent_case
Example #20
0
 def create_case(self):
     return CommCareCase(
         case_id='redwoman',
         domain=self.domain,
         opened_on=datetime.datetime(2016, 5, 31),
         modified_on=datetime.datetime(2016, 5, 31),
         type='priestess',
         closed=False,
         name='melisandre',
         owner_id='lordoflight',
         indices=[{
             'identifier': 'advisor',
             'referenced_type': 'human',
             'referenced_id': 'stannis',
             'relationship': 'extension',
         }],
         case_json={
             'power': 'prophecy',
             'hometown': 'asshai'
         },
     )
class TestGetCaseTriggerInfo(TestCase):
    def setUp(self):
        self.case_type = CaseType.objects.create(domain=DOMAIN, name='foo')
        self.resource_type = FHIRResourceType.objects.create(
            domain=DOMAIN,
            case_type=self.case_type,
            name='Foo',
        )
        for name in ('een', 'twee', 'drie'):
            prop = CaseProperty.objects.create(
                case_type=self.case_type,
                name=name,
            )
            FHIRResourceProperty.objects.create(
                resource_type=self.resource_type,
                case_property=prop,
                jsonpath=f'$.{name}',
            )

    def tearDown(self):
        self.case_type.delete()

    def test_case_properties(self):
        case = CommCareCase(case_id=str(uuid4()),
                            domain=DOMAIN,
                            type='foo',
                            name='bar',
                            case_json={
                                'een': 1,
                                'twee': 2,
                                'drie': 3,
                                'vier': 4,
                                'vyf': 5,
                                'ses': 6,
                            })
        info = get_case_trigger_info(case, self.resource_type)
        for name in ('een', 'twee', 'drie'):
            self.assertIn(name, info.extra_fields)
        for name in ('vier', 'vyf', 'ses'):
            self.assertNotIn(name, info.extra_fields)
Example #22
0
    def _create_case(self, case_type=None, user_id=None, case_id=None):
        case_id = case_id or uuid.uuid4().hex
        user_id = user_id or 'mr_wednesday'
        utcnow = datetime.utcnow()

        case = CommCareCase(case_id=case_id,
                            domain=self.DOMAIN,
                            type=case_type or '',
                            owner_id=user_id,
                            opened_on=utcnow,
                            modified_on=utcnow,
                            modified_by=utcnow,
                            server_modified_on=utcnow)

        form = self._create_form(user_id, utcnow)
        trans = self._create_case_transaction(case,
                                              form,
                                              utcnow,
                                              action_types=[128])
        self._save(form, case, trans)

        return CommCareCase.objects.get_case(case_id)
Example #23
0
    def setUpClass(cls):
        cls.factory = AppFactory(domain=cls.domain)
        cls.app = cls.factory.app
        cls.module, cls.basic_form = cls.factory.new_basic_module(
            'basic', 'patient')

        # necessary to render_xform
        builder = XFormBuilder(cls.basic_form.name)
        builder.new_question(name='name', label='Name')
        cls.basic_form.source = builder.tostring(
            pretty_print=True).decode('utf-8')

        cls.phone_number = "+919999999999"
        cls.case_id = uuid.uuid4().hex
        cls.recipient = None

        cls.case = CommCareCase(domain=cls.domain,
                                case_id=cls.case_id,
                                case_json={'language_code': 'fr'})
        cls.web_user = WebUser(username='******',
                               _id=uuid.uuid4().hex,
                               language='hin')
Example #24
0
class TestCaseESAccessors(BaseESAccessorsTest):

    es_index_infos = [CASE_INDEX_INFO, USER_INDEX_INFO]

    def setUp(self):
        super(TestCaseESAccessors, self).setUp()
        self.owner_id = 'batman'
        self.user_id = 'robin'
        self.case_type = 'heroes'

    def _send_case_to_es(self,
                         domain=None,
                         owner_id=None,
                         user_id=None,
                         case_type=None,
                         opened_on=None,
                         closed_on=None,
                         modified_on=None):

        case = CommCareCase(case_id=uuid.uuid4().hex,
                            domain=domain or self.domain,
                            owner_id=owner_id or self.owner_id,
                            modified_by=user_id or self.user_id,
                            type=case_type or self.case_type,
                            opened_on=opened_on or datetime.now(),
                            opened_by=user_id or self.user_id,
                            closed_on=closed_on,
                            modified_on=modified_on or datetime.now(),
                            closed_by=user_id or self.user_id,
                            server_modified_on=datetime.utcnow(),
                            closed=bool(closed_on))

        case.track_create(
            CaseTransaction(
                type=CaseTransaction.TYPE_FORM,
                form_id=uuid.uuid4().hex,
                case=case,
                server_date=opened_on,
            ))
Example #25
0
    def get_cases_from_forms(case_db, xforms):
        """Get all cases affected by the forms. Includes new cases, updated cases.
        """
        touched_cases = {}
        if len(xforms) > 1:
            domain = xforms[0].domain
            affected_cases = set()
            deprecated_form = None
            for xform in xforms:
                if xform.is_deprecated:
                    deprecated_form = xform
                if not (xform.is_deprecated and xform.problem):
                    # don't process deprecated forms which have errors.
                    # see http://manage.dimagi.com/default.asp?243382 for context.
                    # note that we have to use .problem instead of .is_error because applying
                    # the state=DEPRECATED overrides state=ERROR
                    affected_cases.update(
                        case_update.id
                        for case_update in get_case_updates(xform))

            rebuild_detail = FormEditRebuild(
                deprecated_form_id=deprecated_form.form_id)
            for case_id in affected_cases:
                case = case_db.get(case_id)
                is_creation = False
                if not case:
                    case = CommCareCase(domain=domain, case_id=case_id)
                    is_creation = True
                    case_db.set(case_id, case)
                previous_owner = case.owner_id
                case, _ = FormProcessorSQL._rebuild_case_from_transactions(
                    case, rebuild_detail, updated_xforms=xforms)
                if case:
                    touched_cases[case.case_id] = CaseUpdateMetadata(
                        case=case,
                        is_creation=is_creation,
                        previous_owner_id=previous_owner,
                        actions={const.CASE_ACTION_REBUILD})
Example #26
0
def _mock_case(case_id, props=None, domain=TARGET_DOMAIN, case_type="patient"):
    props = props if props is not None else {
        "existing_prop": uuid.uuid4().hex,
        "existing_blank_prop": ""
    }
    case = CommCareCase(
        domain=domain, type=case_type, case_id=case_id,
        name=None, external_id=None,
        case_json=props,
    )
    case.cached_indices = [
        CommCareCaseIndex(
            domain=domain, case_id=case_id,
            identifier="parent_c", referenced_type="parent_type",
            referenced_id="parent_case_id", relationship_id=CommCareCaseIndex.CHILD
        ),
        CommCareCaseIndex(
            domain=domain, case_id=case_id,
            identifier="host_c", referenced_type="host_type",
            referenced_id="host_case_id", relationship_id=CommCareCaseIndex.EXTENSION
        )
    ]
    return case
Example #27
0
    def _setup_case(self, cases=None):

        modify_date = datetime.utcnow()

        cases = cases or [(None, None)]
        for owner_id, case_id in cases:
            kwargs = {}
            if owner_id:
                kwargs['owner_id'] = owner_id
            backend_case = CommCareCase(
                case_id=case_id if case_id else uuid.uuid4().hex,
                domain=self.domain.name,
                modified_on=modify_date,
                server_modified_on=modify_date,
                **kwargs)
            backend_case.save()

            translated_doc = transform_case_for_elasticsearch(
                backend_case.to_json())

            send_to_elasticsearch('cases', translated_doc)
        self.es.indices.refresh(CASE_INDEX_INFO.index)
        return backend_case
Example #28
0
    def test_registration_payload(self, payload_doc_mock, connection_settings_mock):
        connection_settings_mock.return_value = ConnectionSettings(password="******")

        case_id = uuid.uuid4().hex
        case_json = {
            'beneficiary_name': 'Nitish Dube',
            'birth_year': '2000',
            'gender_id': '1',
            'mobile_number': '9999999999',
            'photo_id_type': '1',
            'photo_id_number': '1234',
            'consent_version': "1"
        }
        case = CommCareCase(domain=self.domain, type='cowin_api_data', case_id=case_id, case_json=case_json,
                            server_modified_on=datetime.datetime.utcnow())
        payload_doc_mock.return_value = case

        repeater = BeneficiaryRegistrationRepeater()
        generator = BeneficiaryRegistrationPayloadGenerator(repeater)
        repeat_record = RepeatRecord()

        self.assertEqual(repeater.get_headers(repeat_record)['X-Api-Key'], "secure-api-key")

        payload = generator.get_payload(repeat_record=None, cowin_api_data_registration_case=case)
        self.assertDictEqual(
            json.loads(payload),
            {
                'name': 'Nitish Dube',
                'birth_year': '2000',
                'gender_id': 1,
                'mobile_number': '9999999999',
                "photo_id_type": 1,
                'photo_id_number': '1234',
                "consent_version": "1"
            }
        )
    def setUpClass(cls):
        super().setUpClass()
        cls.domain = 'case-list-test'
        cls.user = WebUser(username='******', domains=[cls.domain])
        cls.user.domain_memberships = [
            DomainMembership(domain=cls.domain, role_id='admin')
        ]
        cls.request_factory = RequestFactory()

        from corehq.apps.reports.tests.data.case_list_report_data import (
            dummy_case_list,
            dummy_user_list,
        )

        for user in dummy_user_list:
            user_obj = CouchUser.get_by_username(user['username'])
            if user_obj:
                user_obj.delete(cls.domain, deleted_by=None)
        cls.user_list = []
        for user in dummy_user_list:
            user_obj = CommCareUser.create(**user) if user['doc_type'] == 'CommcareUser'\
                else WebUser.create(**user)
            user_obj.save()
            cls.user_list.append(user_obj)

        cls.case_list = []
        for case in dummy_case_list:
            cls.case_list.append(CommCareCase(**case))
        cls.es = get_es_new()
        ensure_index_deleted(USER_INDEX)
        ensure_index_deleted(CASE_INDEX)
        initialize_index_and_mapping(cls.es, USER_INDEX_INFO)
        initialize_index_and_mapping(cls.es, CASE_INDEX_INFO)
        initialize_index_and_mapping(cls.es, GROUP_INDEX_INFO)
        cls._send_users_to_es()
        cls._send_cases_to_es()
    def test_simple_case_management(self, datetime_mock):
        fake_time_now = datetime(2015, 4, 24, 12, 30, 8, 24886)
        datetime_mock.utcnow.return_value = fake_time_now
        index_column_id = 'indices.app_data_parent'
        app = self.app
        data_sources = get_case_data_sources(app)
        self.assertEqual(2, len(data_sources))
        data_source = data_sources[self.case_type]
        self.assertEqual(self.domain, data_source.domain)
        self.assertEqual('CommCareCase', data_source.referenced_doc_type)
        self.assertEqual(self.case_type, data_source.table_id)
        self.assertEqual(self.case_type, data_source.display_name)

        # test the filter
        self.assertTrue(
            data_source.filter({
                'doc_type': 'CommCareCase',
                'domain': self.domain,
                'type': self.case_type
            }))
        self.assertFalse(
            data_source.filter({
                'doc_type': 'CommCareCase',
                'domain': 'wrong-domain',
                'type': self.case_type
            }))
        self.assertFalse(
            data_source.filter({
                'doc_type': 'NotCommCareCase',
                'domain': self.domain,
                'type': self.case_type
            }))
        self.assertFalse(
            data_source.filter({
                'doc_type': 'CommCareCase',
                'domain': self.domain,
                'type': 'wrong-type'
            }))

        # check the indicators
        datetime_columns = [
            "last_modified_date", "opened_date", "closed_date", "inserted_at",
            "server_last_modified_date"
        ]
        expected_columns = set(datetime_columns + [
            "doc_id",
            "case_type",
            "last_modified_by_user_id",
            "opened_by_user_id",
            "closed",
            "closed_by_user_id",
            "owner_id",
            "name",
            "state",
            "external_id",
            "count",
        ] + list(self.case_properties.keys()) + [index_column_id])
        self.assertEqual(
            expected_columns,
            set(col_back.id for col_back in data_source.get_columns()))

        modified_on = datetime(2014, 11, 12, 15, 37, 49)
        opened_on = datetime(2014, 11, 11, 23, 34, 34, 25)
        parent_id = 'fake-parent-id'
        sample_doc = CommCareCase(case_id='some-doc-id',
                                  modified_on=modified_on,
                                  opened_on=opened_on,
                                  user_id="23407238074",
                                  owner_id="0923409230948",
                                  name="priority ticket",
                                  domain=app.domain,
                                  type=self.case_type,
                                  case_json={
                                      'first_name': 'test first',
                                      'last_name': 'test last',
                                      'children': '3',
                                      'dob': '2001-01-01',
                                  },
                                  indices=[{
                                      'identifier': 'parent',
                                      'referenced_type': self.parent_type,
                                      'referenced_id': parent_id,
                                      'relationship': 'child',
                                  }]).to_json()

        def _get_column_property(column):
            # this is the mapping of column id to case property path
            property_map = {
                c.label: c.item.path[0].name
                for c in MAIN_CASE_TABLE_PROPERTIES
            }
            property_map.update({
                'doc_id': '_id',
            })
            return property_map.get(column.id, column.id)

        default_case_property_datatypes = DEFAULT_CASE_PROPERTY_DATATYPES
        [row] = data_source.get_all_values(sample_doc)
        for result in row:
            if result.column.id in datetime_columns:
                self.assertEqual(result.column.datatype, 'datetime')
            if result.column.id == "inserted_at":
                self.assertEqual(fake_time_now, result.value)
            if result.column.id == index_column_id:
                self.assertEqual(parent_id, result.value)
            elif result.column.id == "last_modified_date":
                self.assertEqual(modified_on, result.value)
            elif result.column.id == "opened_date":
                self.assertEqual(opened_on, result.value)
            elif result.column.id == "count":
                self.assertEqual(1, result.value)
            elif result.column.id not in [
                    "repeat_iteration", "inserted_at", 'closed'
            ]:
                self.assertEqual(
                    sample_doc[_get_column_property(result.column)],
                    result.value)
                if result.column.id in default_case_property_datatypes:
                    self.assertEqual(
                        result.column.datatype,
                        default_case_property_datatypes[result.column.id])