def test_indices(self): parents = ['catelyn', 'ned', 'cersei', 'jaimie'] index_structure = { 'bran': [ {'identifier': 'mom', 'referenced_id': 'catelyn'}, {'identifier': 'dad', 'referenced_id': 'ned'}, ], 'myrcella': [ {'identifier': 'mom', 'referenced_id': 'cersei'}, {'identifier': 'dad', 'referenced_id': 'jaimie'}, ] } sync_log = SyncLog( cases_on_phone=[ CaseState(case_id='bran', indices=[ CommCareCaseIndex(**args) for args in index_structure['bran'] ]), CaseState(case_id='myrcella', indices=[ CommCareCaseIndex(**args) for args in index_structure['myrcella'] ]) ], dependent_cases_on_phone=[ CaseState(case_id=parent) for parent in parents ] ) migrated = SimplifiedSyncLog.from_other_format(sync_log) for case_id, indices in index_structure.items(): self.assertTrue(case_id in migrated.index_tree.indices) for index in indices: self.assertEqual(index['referenced_id'], migrated.index_tree.indices[case_id][index['identifier']]) for parent in parents: self.assertTrue(parent in migrated.case_ids_on_phone) self.assertTrue(parent in migrated.dependent_case_ids_on_phone)
def test_archive(self): log = SyncLog(cases_on_phone=[CaseState(case_id="c1", indices=[CommCareCaseIndex(identifier="d1-id", referenced_id="d1")]), CaseState(case_id="c2", indices=[CommCareCaseIndex(identifier="d1-id", referenced_id="d1"), CommCareCaseIndex(identifier="d2-id", referenced_id="d2")]), CaseState(case_id="c3", indices=[])], dependent_cases_on_phone=[CaseState(case_id="d1", indices=[]), CaseState(case_id="d2", indices=[])]) self.assertEqual(5, len(log.get_footprint_of_cases_on_phone())) self.assertTrue("c3" in log.get_footprint_of_cases_on_phone()) log.archive_case("c3") self.assertEqual(4, len(log.get_footprint_of_cases_on_phone())) self.assertFalse("c3" in log.get_footprint_of_cases_on_phone()) self.assertTrue("c2" in log.get_footprint_of_cases_on_phone()) self.assertTrue("d2" in log.get_footprint_of_cases_on_phone()) log.archive_case("c2") self.assertEqual(2, len(log.get_footprint_of_cases_on_phone())) self.assertFalse("c2" in log.get_footprint_of_cases_on_phone()) self.assertFalse("d2" in log.get_footprint_of_cases_on_phone()) self.assertTrue("c1" in log.get_footprint_of_cases_on_phone()) self.assertTrue("d1" in log.get_footprint_of_cases_on_phone()) log.archive_case("c1") self.assertEqual(0, len(log.get_footprint_of_cases_on_phone()))
def setUp(self): self.i1 = CommCareCaseIndex(identifier='i1', referenced_type='t1', referenced_id='id1') self.i2 = CommCareCaseIndex(identifier='i2', referenced_type='t2', referenced_id='id2') self.case = CommCareCase(indices=[self.i1, self.i2])
def setUp(self): now = datetime.utcnow() self.parent_case_id = str(uuid4()) self.parent_case = CommCareCase( _id=self.parent_case_id, domain=DOMAIN, type='person', name='Ted', owner_id=str(uuid4()), modified_on=now, server_modified_on=now, ) self.parent_case.save() self.child_case_1 = CommCareCase( case_id='111111111', domain=DOMAIN, type='person_name', name='Theodore', given_names='Theodore John', family_name='Kaczynski', indices=[ CommCareCaseIndex( identifier='parent', referenced_type='person', referenced_id=self.parent_case_id, ) ], owner_id=str(uuid4()), modified_on=now, server_modified_on=now, ) self.child_case_1.save() self.child_case_2 = CommCareCase( case_id='222222222', domain=DOMAIN, type='person_name', name='Unabomber', given_names='Unabomber', indices=[ CommCareCaseIndex( identifier='parent', referenced_type='person', referenced_id=self.parent_case_id, ) ], owner_id=str(uuid4()), modified_on=now, server_modified_on=now, ) self.child_case_2.save()
def test_complex_index(self): cp = CommCareCase( _id='parent', name='parent', type='parent', ) cp.save() # cases processed according to ID order so ensure that this case is # processed after the task case by making its ID sort after task ID cc = CommCareCase( _id='z_goal', name='goal', type='goal', indices=[ CommCareCaseIndex(identifier='parent', referenced_type='parent', referenced_id='parent') ], ) cc.save() cc = CommCareCase( _id='task1', name='task1', type='task', indices=[ CommCareCaseIndex(identifier='goal', referenced_type='goal', referenced_id='z_goal'), CommCareCaseIndex(identifier='parent', referenced_type='parent', referenced_id='parent') ], ) cc.save() # with 'ignore_relationship_types' if a case got processed along the ignored relationship first # then it got marked as 'seen' and would be not be processed again when it came to the correct relationship type_info = { 'task': { 'ignore_relationship_types': ['parent'] }, } hierarchy = get_case_hierarchy(cp, type_info) self.assertEqual(3, len(hierarchy['case_list'])) self.assertEqual(1, len(hierarchy['child_cases'])) self.assertEqual(2, len(hierarchy['child_cases'][0]['case_list'])) self.assertEqual(1, len(hierarchy['child_cases'][0]['child_cases']))
def reverse_indices(db, case): return db.view( "case/related", key=[case.domain, case._id, "reverse_index"], reduce=False, wrapper=lambda r: CommCareCaseIndex.wrap(r["value"]), ).all()
def setUp(self): now = datetime.utcnow() owner_id = str(uuid4()) self.parent_case_id = str(uuid4()) self.parent_case = CommCareCase( _id=self.parent_case_id, domain=DOMAIN, type='person', name='Beth', owner_id=owner_id, modified_on=now, server_modified_on=now, ) self.parent_case.save() self.child_case_id = str(uuid4()) self.child_case = CommCareCase( _id=self.child_case_id, domain=DOMAIN, type='vitals', temperature=36.1, indices=[ CommCareCaseIndex( identifier='parent', referenced_type='person', referenced_id=self.parent_case_id, ) ], owner_id=owner_id, modified_on=now, server_modified_on=now, ) self.child_case.save()
def from_parsed_action(cls, date, user_id, xformdoc, action): if not action.action_type_slug in const.CASE_ACTIONS: raise ValueError("%s not a valid case action!" % action.action_type_slug) ret = CommCareCaseAction(action_type=action.action_type_slug, date=date, user_id=user_id) ret.server_date = xformdoc.received_on ret.xform_id = xformdoc.form_id ret.xform_xmlns = xformdoc.xmlns ret.xform_name = getattr(xformdoc, 'name', '') ret.updated_known_properties = action.get_known_properties() ret.updated_unknown_properties = action.dynamic_properties ret.indices = [ CommCareCaseIndex.from_case_index_update(i) for i in action.indices ] ret.attachments = dict( (attach_id, CommCareCaseAttachment.from_case_index_update(attach)) for attach_id, attach in action.attachments.items()) if hasattr(xformdoc, "last_sync_token"): ret.sync_log_id = xformdoc.last_sync_token return ret
def test_update_dependent_case(self): sync_log = SyncLog( cases_on_phone=[ CaseState( case_id='bran', indices=[ CommCareCaseIndex(identifier='legs', referenced_id='hodor') ], ), ], dependent_cases_on_phone=[CaseState(case_id='hodor')], user_id="someuser") xform_id = uuid.uuid4().hex xform = XFormInstance(_id=xform_id) form_actions = [CommCareCaseAction(action_type=CASE_ACTION_UPDATE, )] with patch.object(CommCareCase, 'get_actions_for_form', return_value=form_actions): parent_case = CommCareCase(_id='hodor') # before this test was added, the following call raised a SyncLogAssertionError on legacy logs. # this test just ensures it doesn't still do that. for log in [ sync_log, SimplifiedSyncLog.from_other_format(sync_log) ]: log.update_phone_lists(xform, [parent_case])
def test_update_dependent_case_owner_still_present(self): dependent_case_state = CaseState(case_id="d1", indices=[]) sync_log = SyncLog(domain="domain", user_id="user", cases_on_phone=[ CaseState(case_id="c1", indices=[ CommCareCaseIndex( identifier="d1-id", referenced_id="d1") ]) ], dependent_cases_on_phone=[dependent_case_state], owner_ids_on_phone=['user1']) xform_id = uuid.uuid4().hex xform = XFormInstance(_id=xform_id) form_actions = [ CommCareCaseAction(action_type=CASE_ACTION_UPDATE, updated_known_properties={'owner_id': 'user2'}) ] with patch.object(CommCareCase, 'get_actions_for_form', return_value=form_actions): parent_case = CommCareCase(_id='d1') # before this test was added, the following call raised a ValueError on legacy logs. for log in [ sync_log, SimplifiedSyncLog.from_other_format(sync_log) ]: log.update_phone_lists(xform, [parent_case]) self.assertIn(dependent_case_state, log.test_only_get_dependent_cases_on_phone())
def indices(self): diffs = [d for d in self.diffs if d.path[0] == "indices"] if not diffs: return for diff in diffs: if diff.path != ["indices", "[*]"]: raise CannotPatch([diff]) if diff.new_value is MISSING and isinstance(diff.old_value, dict): yield CommCareCaseIndex.wrap(diff.old_value) elif diff.old_value is MISSING and isinstance(diff.new_value, dict): yield CommCareCaseIndex( identifier=diff.new_value["identifier"], referenced_type="", ) else: raise CannotPatch([diff])
def test_patch_missing_case_with_index(self): self.submit_form(make_test_form("form-1", case_id="case-1")) case = CaseAccessorCouch.get_case("case-1") case.indices = [ CommCareCaseIndex.wrap({ "doc_type": "CommCareCaseIndex", "identifier": "parent", "referenced_type": "household", "referenced_id": "a53346d5", "relationship": "child", }) ] case.save() FormAccessors(self.domain_name).soft_delete_forms(['form-1'], datetime.utcnow(), 'test-deletion') self.do_migration(diffs=IGNORE) self.compare_diffs(changes=[ Diff('case-1', 'missing', ['*'], old='*', new=MISSING, reason="deleted forms"), ]) self.do_case_patch() self.compare_diffs() self.assert_patched_cases(["case-1"])
def indices(self): diffs = [d for d in self.diffs if d.path[0] == "indices"] if not diffs: return for diff in diffs: if diff.path != ["indices", "[*]"] or diff.new_value is not MISSING: raise CannotPatch([diff]) yield CommCareCaseIndex.wrap(diff.old_value)
def test_prescription_with_date_fulfilled(self): EpisodePrescription.objects.create( id=1, beneficiaryId=self.beneficiary.caseId, creationDate=datetime(2017, 5, 26), numberOfDays=2, numberOfDaysPrescribed='2', prescriptionID=3, pricePerUnit=0.5, productID=4, productName='drug name', refill_Index=5, voucherID=6, ) Voucher.objects.create( id=2, creationDate=datetime(2017, 5, 31), modificationDate=datetime(2017, 5, 31), voucherCreatedDate=datetime(2017, 5, 31), voucherNumber=6, voucherStatusId='3', voucherUsedDate=datetime(2017, 6, 1), ) call_command('create_cases_by_beneficiary', self.domain, 'tests') self.assertEqual(len(self.case_accessor.get_case_ids_in_domain(type='person')), 1) self.assertEqual(len(self.case_accessor.get_case_ids_in_domain(type='occurrence')), 1) episode_case_ids = self.case_accessor.get_case_ids_in_domain(type='episode') self.assertEqual(len(episode_case_ids), 1) episode_case = self.case_accessor.get_case(episode_case_ids[0]) prescription_case_ids = self.case_accessor.get_case_ids_in_domain(type='prescription') self.assertEqual(len(prescription_case_ids), 1) prescription_case = self.case_accessor.get_case(prescription_case_ids[0]) self.assertTrue(prescription_case.closed) self.assertIsNone(prescription_case.external_id) self.assertEqual(prescription_case.name, 'drug name') self.assertEqual(prescription_case.owner_id, '-') self.assertEqual(prescription_case.dynamic_case_properties(), OrderedDict([ ('date_fulfilled', '2017-06-01'), ('date_ordered', '2017-05-26'), ('migration_comment', 'tests'), ('migration_created_case', 'true'), ('migration_created_from_record', '3'), ('number_of_days_prescribed', '2'), ])) self.assertEqual(len(prescription_case.indices), 1) self._assertIndexEqual( prescription_case.indices[0], CommCareCaseIndex( identifier='episode_of_prescription', referenced_type='episode', referenced_id=episode_case.get_id, relationship='extension', ) ) self.assertEqual(len(prescription_case.xform_ids), 1)
def reverse_indices(db, case, wrap=True): kwargs = { 'wrapper': lambda r: CommCareCaseIndex.wrap(r['value']) if wrap else r['value'] } return db.view( "case/related", key=[case['domain'], case['_id'], "reverse_index"], reduce=False, **kwargs ).all()
def test_dependent_cases(self): log = SyncLog(cases_on_phone=[CaseState(case_id="c1", indices=[CommCareCaseIndex(identifier="d1-id", referenced_id="d1")])], dependent_cases_on_phone=[CaseState(case_id="d1", indices=[]), CaseState(case_id="d2", indices=[])]) # d1 counts because it's referenced, d2 doesn't self.assertEqual(2, len(log.get_footprint_of_cases_on_phone())) self.assertTrue("d1" in log.get_footprint_of_cases_on_phone()) self.assertFalse("d2" in log.get_footprint_of_cases_on_phone())
def test_followup_end_of_cp(self): followup = self._create_diagnostic_followup() followup.IntervalId = 4 followup.SmearResult = 98 followup.save() call_command('create_enikshay_cases', self.domain, 'test_migration') self.assertEqual( len(self.case_accessor.get_case_ids_in_domain(type='person')), 1) occurrence_cases = self.case_accessor.get_case_ids_in_domain( type='occurrence') self.assertEqual(len(occurrence_cases), 1) occurrence_case_id = occurrence_cases[0] episode_case_ids = self.case_accessor.get_case_ids_in_domain( type='episode') self.assertEqual(len(episode_case_ids), 1) self.assertEqual( len( self.case_accessor.get_case_ids_in_domain( type='drtb-hiv-referral')), 0) test_case_ids = self.case_accessor.get_case_ids_in_domain(type='test') self.assertEqual(len(test_case_ids), 1) test_case = self.case_accessor.get_case(test_case_ids[0]) self.assertEqual(test_case.closed, False) self.assertEqual(test_case.name, '2017-04-10') self.assertEqual(test_case.opened_on, datetime(2017, 4, 10)) self.assertEqual(test_case.owner_id, '-') self.assertEqual( test_case.dynamic_case_properties(), OrderedDict([ ('date_reported', '2017-04-10'), ('date_tested', '2017-04-10'), ('episode_type_at_request', 'confirmed_tb'), ('follow_up_test_reason', 'end_of_cp'), ('lab_serial_number', '2073'), ('migration_comment', 'test_migration'), ('migration_created_case', 'true'), ('migration_created_from_id', str(followup.id)), ('migration_created_from_record', self.patient_detail.PregId), ('purpose_of_testing', 'follow_up'), ('result_grade', 'Pos'), ('result_recorded', 'yes'), ('testing_facility_id', '1'), ])) self.assertEqual(len(test_case.indices), 1) self._assertIndexEqual( test_case.indices[0], CommCareCaseIndex( identifier='host', referenced_type='occurrence', referenced_id=occurrence_case_id, relationship='extension', ))
def setUp(self): super(TestReverseIndexedCases, self).setUp() self.domain = 'domain' self.factory = CaseFactory(self.domain) self.indexed_case_id = uuid.uuid4().hex self.index = CommCareCaseIndex(identifier="host", referenced_type="host", relationship=CASE_INDEX_EXTENSION, referenced_id=self.indexed_case_id) self.case = CommCareCase(domain=self.domain, indices=[self.index]) self.case.save()
def test_prescription(self): EpisodePrescription.objects.create( id=1, beneficiaryId=self.beneficiary, numberOfDays=2, prescriptionID=3, pricePerUnit=0.5, productID=4, productName='drug name', refill_Index=5, voucherID=6, ) call_command('create_cases_by_beneficiary', self.domain) self.assertEqual( len(self.case_accessor.get_case_ids_in_domain(type='person')), 1) self.assertEqual( len(self.case_accessor.get_case_ids_in_domain(type='occurrence')), 1) episode_case_ids = self.case_accessor.get_case_ids_in_domain( type='episode') self.assertEqual(len(episode_case_ids), 1) episode_case = self.case_accessor.get_case(episode_case_ids[0]) prescription_case_ids = self.case_accessor.get_case_ids_in_domain( type='prescription') self.assertEqual(len(prescription_case_ids), 1) prescription_case = self.case_accessor.get_case( prescription_case_ids[0]) self.assertFalse(prescription_case.closed) # TODO self.assertIsNone(prescription_case.external_id) self.assertEqual(prescription_case.name, 'drug name') # self.assertEqual(adherence_case.opened_on, '') # TODO self.assertEqual(prescription_case.owner_id, '-') self.assertEqual( prescription_case.dynamic_case_properties(), OrderedDict([ ('migration_created_case', 'true'), ('migration_created_from_record', '3'), ])) self.assertEqual(len(prescription_case.indices), 1) self._assertIndexEqual( prescription_case.indices[0], CommCareCaseIndex( identifier='episode_of_prescription', referenced_type='episode', referenced_id=episode_case.get_id, relationship='extension', )) self.assertEqual(len(prescription_case.xform_ids), 1)
def test_dependent_cases_on_phone(self): sync_log = SyncLog( cases_on_phone=[ CaseState( case_id='bran', indices=[CommCareCaseIndex(identifier='legs', referenced_id='hodor')], ), ], dependent_cases_on_phone=[CaseState(case_id='hodor')] ) migrated = SimplifiedSyncLog.from_other_format(sync_log) self.assertTrue('bran' in migrated.case_ids_on_phone) self.assertTrue('hodor' in migrated.case_ids_on_phone) self.assertTrue('hodor' in migrated.dependent_case_ids_on_phone)
def test_patch_case_index(self): self.submit_form(make_test_form("form-1", case_id="case-1")) self.do_migration(case_diff="none") index = { "doc_type": "CommCareCaseIndex", "identifier": "parent", "referenced_type": "household", "referenced_id": "a53346d5", "relationship": "child", } with self.augmented_couch_case("case-1") as case: case.indices = [CommCareCaseIndex.wrap(index)] case.save() self.do_case_diffs()
def test_recursive_indexes(self): c = CommCareCase( _id='infinite-recursion', name='infinite_recursion', type='bug', indices=[ CommCareCaseIndex(identifier='self', referenced_type='bug', referenced_id='infinite-recursion') ], ) c.save() # this call used to fail with infinite recursion hierarchy = get_case_hierarchy(c, {}) self.assertEqual(1, len(hierarchy['case_list']))
def from_parsed_action(cls, action_type, date, xformdoc, action): if not action_type in const.CASE_ACTIONS: raise ValueError("%s not a valid case action!") ret = CommCareCaseAction(action_type=action_type, date=date, xform_id=xformdoc.get_id) def _couchify(d): return dict((k, couchable_property(v)) for k, v in d.items()) ret.server_date = datetime.utcnow() ret.updated_known_properties = _couchify(action.get_known_properties()) ret.updated_unknown_properties = _couchify(action.dynamic_properties) ret.indices = [CommCareCaseIndex.from_case_index_update(i) for i in action.indices] if hasattr(xformdoc, "last_sync_token"): ret.sync_log_id = xformdoc.last_sync_token return ret
def testClosedParentIndex(self): """ Tests that things work properly when you have a reference to the parent case in a child, even if it's closed. """ # first create the parent case parent_id = "mommy" self._createCaseStubs([parent_id]) self._testUpdate(self.sync_log.get_id, {parent_id: []}) # create the child child_id = "baby" index_id = 'my_mom_is' child = CaseBlock( create=True, case_id=child_id, user_id=USER_ID, version=V2, index={ index_id: (PARENT_TYPE, parent_id) }, ).as_xml() self._postFakeWithSyncToken(child, self.sync_log.get_id) index_ref = CommCareCaseIndex(identifier=index_id, referenced_type=PARENT_TYPE, referenced_id=parent_id) self._testUpdate(self.sync_log.get_id, { parent_id: [], child_id: [index_ref] }) # close the mother case close = CaseBlock(create=False, case_id=parent_id, user_id=USER_ID, version=V2, close=True).as_xml() self._postFakeWithSyncToken(close, self.sync_log.get_id) self._testUpdate(self.sync_log.get_id, {child_id: [index_ref]}, {parent_id: []}) # try a clean restore again assert_user_has_case(self, self.user, parent_id) assert_user_has_case(self, self.user, child_id)
def setUp(self): self.case = CommCareCase(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=[ CommCareCaseIndex( identifier='advisor', referenced_type='human', referenced_id='stannis', relationship='extension', ) ]) self.case._id = 'redwoman' self.case.power = 'prophecy' self.case.hometown = 'asshai'
def from_parsed_action(cls, date, user_id, xformdoc, action): if not action.action_type_slug in const.CASE_ACTIONS: raise ValueError("%s not a valid case action!" % action.action_type_slug) ret = CommCareCaseAction(action_type=action.action_type_slug, date=date, user_id=user_id) ret.server_date = xformdoc.received_on ret.xform_id = xformdoc.get_id ret.xform_xmlns = xformdoc.xmlns ret.xform_name = xformdoc.name ret.updated_known_properties = action.get_known_properties() ret.updated_unknown_properties = action.dynamic_properties ret.indices = [CommCareCaseIndex.from_case_index_update(i) for i in action.indices] ret.attachments = dict((attach_id, CommCareCaseAttachment.from_case_index_update(attach)) for attach_id, attach in action.attachments.items()) if hasattr(xformdoc, "last_sync_token"): ret.sync_log_id = xformdoc.last_sync_token return ret
def testAssignToNewOwner(self): # first create the parent case parent_id = "mommy" self._createCaseStubs([parent_id]) self._testUpdate(self.sync_log.get_id, {parent_id: []}) # create the child child_id = "baby" index_id = 'my_mom_is' self._postFakeWithSyncToken( CaseBlock( create=True, case_id=child_id, user_id=USER_ID, version=V2, index={ index_id: (PARENT_TYPE, parent_id) }, ).as_xml(), self.sync_log.get_id) index_ref = CommCareCaseIndex(identifier=index_id, referenced_type=PARENT_TYPE, referenced_id=parent_id) # should be there self._testUpdate(self.sync_log.get_id, { parent_id: [], child_id: [index_ref] }) # assign to new owner new_owner = "not_mine" self._postFakeWithSyncToken( CaseBlock(create=False, case_id=child_id, user_id=USER_ID, version=V2, owner_id=new_owner).as_xml(), self.sync_log.get_id) # should be moved self._testUpdate(self.sync_log.get_id, {parent_id: []}, {child_id: [index_ref]})
def test_normal_index(self): cp = CommCareCase( _id='parent', name='parent', type='parent', ) cp.save() cc = CommCareCase( _id='child', name='child', type='child', indices=[ CommCareCaseIndex(identifier='parent', referenced_type='parent', referenced_id='parent') ], ) cc.save() hierarchy = get_case_hierarchy(cp, {}) self.assertEqual(2, len(hierarchy['case_list'])) self.assertEqual(1, len(hierarchy['child_cases']))
def indices(self): from casexml.apps.case.sharedmodels import CommCareCaseIndex return [ CommCareCaseIndex.wrap(index) for index in self._data['indices'] ]
def test_closed_adherence(self, mock_today): mock_today.today.return_value = date(2017, 6, 1) episode = Episode.objects.create( adherenceScore=0.5, alertFrequencyId=2, basisOfDiagnosis='Clinical - Other', beneficiaryID=self.beneficiary.caseId, creationDate=datetime(2017, 4, 20), dateOfDiagnosis=datetime(2017, 4, 18), dstStatus='Rifampicin sensitive', episodeDisplayID=3, episodeID=1, extraPulmonary='Abdomen', hiv='Negative', lastMonthAdherencePct=0.6, lastTwoWeeksAdherencePct=0.7, missedDosesPct=0.8, newOrRetreatment='New', nikshayID='02139-02215', patientWeight=50, rxStartDate=datetime(2017, 4, 19), site='Extrapulmonary', unknownAdherencePct=0.9, unresolvedMissedDosesPct=0.1, ) Adherence.objects.create( adherenceId=5, creationDate=datetime(2017, 4, 21), dosageStatusId=0, doseDate=datetime(2017, 4, 22), doseReasonId=3, episodeId=episode.episodeID, reportingMechanismId=86, ) call_command('create_cases_by_beneficiary', self.domain, 'tests') self.assertEqual(len(self.case_accessor.get_case_ids_in_domain(type='person')), 1) self.assertEqual(len(self.case_accessor.get_case_ids_in_domain(type='occurrence')), 1) episode_case_ids = self.case_accessor.get_case_ids_in_domain(type='episode') self.assertEqual(len(episode_case_ids), 1) episode_case = self.case_accessor.get_case(episode_case_ids[0]) self.assertEqual(episode_case.dynamic_case_properties()['adherence_total_doses_taken'], '1') adherence_case_ids = self.case_accessor.get_case_ids_in_domain(type='adherence') self.assertEqual(len(adherence_case_ids), 1) adherence_case = self.case_accessor.get_case(adherence_case_ids[0]) self.assertTrue(adherence_case.closed) self.assertIsNone(adherence_case.external_id) self.assertEqual(adherence_case.name, '2017-04-22') self.assertEqual(adherence_case.opened_on, datetime(2017, 4, 21)) self.assertEqual(adherence_case.owner_id, '-') self.assertEqual(adherence_case.dynamic_case_properties(), OrderedDict([ ('adherence_closure_reason', 'historical'), ('adherence_date', '2017-04-22'), ('adherence_report_source', 'treatment_supervisor'), ('adherence_source', 'enikshay'), ('adherence_value', 'directly_observed_dose'), ('migration_comment', 'tests'), ('migration_created_case', 'true'), ('migration_created_from_record', '5'), ])) self.assertEqual(len(adherence_case.indices), 1) self._assertIndexEqual( adherence_case.indices[0], CommCareCaseIndex( identifier='host', referenced_type='episode', referenced_id=episode_case.get_id, relationship='extension', ) ) self.assertEqual(len(adherence_case.xform_ids), 1)
def test_create_cases_for_beneficiary(self, mock_counter, mock_datetime): mock_counter.get_next_counter.return_value = 4 mock_datetime.utcnow.return_value = datetime(2016, 9, 8, 1, 2, 3, 4123) creating_loc = SQLLocation.active_objects.create( domain=self.domain, location_type=LocationType.objects.get(code='pcp'), name='creating location', site_code='2', user_id='dummy_user_id', ) creating_agency = Agency.objects.create( agencyId=2, agencyTypeId='ATPR', agencySubTypeId='PRQP', creationDate=datetime(2017, 5, 1), dateOfRegn=datetime(2017, 5, 1), modificationDate=datetime(2017, 5, 1), nikshayId='123457', organisationId=2, parentAgencyId=3, subOrganisationId=4, ) UserDetail.objects.create( id=1, agencyId=creating_agency.agencyId, isPrimary=True, motechUserName='******', organisationId=2, passwordResetFlag=False, pincode=3, subOrganisationId=4, userId=5, valid=True, ) Episode.objects.create( adherenceScore=0.5, alertFrequencyId=2, basisOfDiagnosis='Clinical - Other', beneficiaryID=self.beneficiary.caseId, creationDate=datetime(2017, 4, 20), dateOfDiagnosis=datetime(2017, 4, 18), diabetes='Yes', dstStatus='Rifampicin sensitive', episodeDisplayID=3, episodeID=6, extraPulmonary='Abdomen', hiv='Negative', lastMonthAdherencePct=0.6, lastTwoWeeksAdherencePct=0.7, missedDosesPct=0.8, newOrRetreatment='New', nikshayID='02139-02215', patientWeight=50, rxStartDate=datetime(2017, 4, 19), rxOutcomeDate=datetime(2017, 5, 19), site='Extrapulmonary', treatmentPhase='Continuation Phase', unknownAdherencePct=0.9, unresolvedMissedDosesPct=0.1, ) call_command('create_cases_by_beneficiary', self.domain, 'tests') person_case_ids = self.case_accessor.get_case_ids_in_domain(type='person') self.assertEqual(len(person_case_ids), 1) person_case = self.case_accessor.get_case(person_case_ids[0]) self.assertFalse(person_case.closed) self.assertIsNone(person_case.external_id) self.assertEqual(person_case.name, 'Nick P') self.assertEqual(person_case.owner_id, self.pcp.location_id) self.assertEqual(person_case.dynamic_case_properties(), OrderedDict([ ('aadhaar_number', '98765'), ('age', '25'), ('age_entered', '25'), ('contact_phone_number', '915432109876'), ('created_by_user_type', 'pcp'), ('current_address', '585 Mass Ave, Suite 4'), ('current_address_postal_code', '822113'), ('current_address_village_town_city', 'Cambridge'), ('current_episode_type', 'confirmed_tb'), ('dataset', 'real'), ('diabetes_status', 'diabetic'), ('dob', '1992-01-02'), ('dob_entered', '1992-01-02'), ('dob_known', 'yes'), ('enrolled_in_private', 'true'), ('facility_assigned_to', self.pcp.location_id), ('first_name', 'Nick'), ('hiv_status', 'non_reactive'), ('husband_father_name', 'Nick Sr.'), ('id_original_beneficiary_count', '4'), ('id_original_device_number', '0'), ('id_original_issuer_number', '7'), ('is_active', 'yes'), ('language_code', 'hin'), ('last_name', 'P'), ('legacy_blockOrHealthPostId', '101'), ('legacy_districtId', '102'), ('legacy_organisationId', '2'), ('legacy_stateId', '103'), ('legacy_subOrganizationId', '3'), ('legacy_wardId', '104'), ('migration_comment', 'tests'), ('migration_created_case', 'true'), ('migration_created_from_record', '3'), ('person_id', 'AAA-KAA-AF'), ('person_id_flat', 'AAAKAAAF'), ('person_id_legacy', '3'), ('person_occurrence_count', '1'), ('phone_number', '5432109876'), ('registered_by', creating_loc.location_id), ('search_name', 'Nick P'), ('secondary_phone', '1234567890'), ('send_alerts', 'yes'), ('sex', 'male'), ])) self.assertEqual(len(person_case.xform_ids), 1) occurrence_case_ids = self.case_accessor.get_case_ids_in_domain(type='occurrence') self.assertEqual(len(occurrence_case_ids), 1) occurrence_case = self.case_accessor.get_case(occurrence_case_ids[0]) self.assertFalse(occurrence_case.closed) self.assertIsNone(occurrence_case.external_id) self.assertEqual(occurrence_case.name, 'Occurrence #1') self.assertEqual(occurrence_case.owner_id, '-') self.assertEqual(occurrence_case.dynamic_case_properties(), OrderedDict([ ('current_episode_type', 'confirmed_tb'), ('legacy_blockOrHealthPostId', '101'), ('legacy_districtId', '102'), ('legacy_organisationId', '2'), ('legacy_stateId', '103'), ('legacy_subOrganizationId', '3'), ('legacy_wardId', '104'), ('migration_comment', 'tests'), ('migration_created_case', 'true'), ('migration_created_from_record', '3'), ('occurrence_episode_count', '1'), ('occurrence_id', '20160908010203004'), ])) self.assertEqual(len(occurrence_case.indices), 1) self._assertIndexEqual( occurrence_case.indices[0], CommCareCaseIndex( identifier='host', referenced_type='person', referenced_id=person_case.get_id, relationship='extension', ) ) self.assertEqual(len(occurrence_case.xform_ids), 1) episode_case_ids = self.case_accessor.get_case_ids_in_domain(type='episode') self.assertEqual(len(episode_case_ids), 1) episode_case = self.case_accessor.get_case(episode_case_ids[0]) self.assertFalse(episode_case.closed) self.assertEqual(episode_case.external_id, '02139-02215') self.assertEqual(episode_case.name, 'Episode #1: Confirmed TB (Patient)') self.assertEqual(episode_case.opened_on, datetime(2017, 4, 19)) self.assertEqual(episode_case.owner_id, '-') self.assertEqual(episode_case.dynamic_case_properties(), OrderedDict([ ('adherence_schedule_date_start', '2017-04-19'), ('adherence_total_doses_taken', '0'), ('adherence_tracking_mechanism', ''), ('basis_of_diagnosis', 'clinical_other'), ('case_definition', 'clinical'), ('created_by_user_type', 'pcp'), ('date_of_diagnosis', '2017-04-18'), ('date_of_mo_signature', '2017-04-17'), ('diagnosing_facility_id', self.pcp.location_id), ('disease_classification', 'extrapulmonary'), ('dots_99_enabled', 'false'), ('dst_status', 'rif_sensitive'), ('enrolled_in_private', 'true'), ('episode_details_complete', 'true'), ('episode_id', '20160908010203004'), ('episode_pending_registration', 'no'), ('episode_type', 'confirmed_tb'), ('legacy_blockOrHealthPostId', '101'), ('legacy_districtId', '102'), ('legacy_organisationId', '2'), ('legacy_stateId', '103'), ('legacy_subOrganizationId', '3'), ('legacy_wardId', '104'), ('migration_comment', 'tests'), ('migration_created_case', 'true'), ('migration_created_from_record', '3'), ('new_retreatment', 'new'), ('nikshay_id', '02139-02215'), ('patient_type', 'new'), ('private_sector_episode_pending_registration', 'no'), ('registered_by', creating_loc.location_id), ('retreatment_reason', ''), ('site', 'extrapulmonary'), ('site_choice', 'abdominal'), ('transfer_in', ''), ('treatment_card_completed_date', '2017-04-20'), ('treatment_initiated', 'yes_pcp'), ('treatment_initiation_date', '2017-04-19'), ('treatment_options', ''), ('treatment_outcome_date', '2017-05-19'), ('treatment_phase', 'continuation_phase_cp'), ('weight', '50'), ])) self.assertEqual(len(episode_case.indices), 1) self._assertIndexEqual( episode_case.indices[0], CommCareCaseIndex( identifier='host', referenced_type='occurrence', referenced_id=occurrence_case.get_id, relationship='extension', ) ) self.assertEqual(len(episode_case.xform_ids), 1)
def get_reverse_indices(case): return [ CommCareCaseIndex.wrap(raw) for raw in get_reverse_indices_json(case) ]
def get_reverse_indices_for_case_id(domain, case_id): return [CommCareCaseIndex.wrap(raw) for raw in get_reverse_indices_json(domain, case_id)]
def get_reverse_indices_for_case_id(domain, case_id): return [ CommCareCaseIndex.wrap(raw) for raw in get_reverse_indices_json(domain, case_id) ]
def wrap_row(row): index = CommCareCaseIndex.wrap(row['value']) index.is_reverse = True return index
def test_case_creation(self, mock_datetime): mock_datetime.utcnow.return_value = datetime(2016, 9, 8, 1, 2, 3, 4123) call_command('create_enikshay_cases', self.domain) person_case_ids = self.case_accessor.get_case_ids_in_domain( type='person') self.assertEqual(1, len(person_case_ids)) person_case = self.case_accessor.get_case(person_case_ids[0]) self.assertEqual( OrderedDict([ ('aadhaar_number', '867386000000'), ('age', '18'), ('age_entered', '18'), ('contact_phone_number', '5432109876'), ('current_address', 'Cambridge MA'), ('current_address_district_choice', self.dto.location_id), ('current_address_state_choice', self.sto.location_id), ('dob', '{}-07-01'.format(datetime.utcnow().year - 18)), ('dob_known', 'no'), ('first_name', 'A B'), ('hiv_status', 'non_reactive'), ('last_name', 'C'), ('migration_created_case', 'true'), ('person_id', 'N-MH-ABD-05-16-0001'), ('phi', 'PHI'), ('secondary_contact_name_address', 'Secondary name, Secondary address'), ('secondary_contact_phone_number', '1234567890'), ('sex', 'male'), ('tu_choice', 'TU'), ]), person_case.dynamic_case_properties()) self.assertEqual('MH-ABD-05-16-0001', person_case.external_id) self.assertEqual('A B C', person_case.name) self.assertEqual(self.phi.location_id, person_case.owner_id) # make sure the case is only created/modified by a single form self.assertEqual(1, len(person_case.xform_ids)) occurrence_case_ids = self.case_accessor.get_case_ids_in_domain( type='occurrence') self.assertEqual(1, len(occurrence_case_ids)) occurrence_case = self.case_accessor.get_case(occurrence_case_ids[0]) self.assertEqual( OrderedDict([ ('current_episode_type', 'confirmed_tb'), ('ihv_date', '2016-12-25'), ('initial_home_visit_status', 'completed'), ('migration_created_case', 'true'), ('occurrence_episode_count', '1'), ('occurrence_id', '20160908010203004'), ]), occurrence_case.dynamic_case_properties()) self.assertEqual('Occurrence #1', occurrence_case.name) self.assertEqual(len(occurrence_case.indices), 1) self._assertIndexEqual( CommCareCaseIndex( identifier='host', referenced_type='person', referenced_id=person_case.get_id, relationship='extension', ), occurrence_case.indices[0]) self.assertEqual('-', occurrence_case.owner_id) # make sure the case is only created/modified by a single form self.assertEqual(1, len(occurrence_case.xform_ids)) episode_case_ids = self.case_accessor.get_case_ids_in_domain( type='episode') self.assertEqual(1, len(episode_case_ids)) episode_case = self.case_accessor.get_case(episode_case_ids[0]) self.assertEqual( OrderedDict([ ('adherence_schedule_date_start', '2016-12-22'), ('date_of_diagnosis', '2016-12-13'), ('date_of_mo_signature', '2016-12-23'), ('disease_classification', 'extra_pulmonary'), ('dots_99_enabled', 'false'), ('episode_pending_registration', 'no'), ('episode_type', 'confirmed_tb'), ('migration_created_case', 'true'), ('nikshay_id', 'MH-ABD-05-16-0001'), ('occupation', 'physical_mathematical_and_engineering'), ('patient_type_choice', 'treatment_after_lfu'), ('site_choice', 'abdominal'), ('treatment_initiated', 'yes_phi'), ('treatment_initiation_date', '2016-12-22'), ('treatment_supporter_designation', 'health_worker'), ('treatment_supporter_first_name', 'Bubble'), ('treatment_supporter_last_name', 'Bubbles'), ('treatment_supporter_mobile_number', '9876543210'), ]), episode_case.dynamic_case_properties()) self.assertEqual('Episode #1: Confirmed TB (Patient)', episode_case.name) self.assertEqual(datetime(2016, 12, 13), episode_case.opened_on) self.assertEqual('-', episode_case.owner_id) self.assertEqual(len(episode_case.indices), 1) self._assertIndexEqual( CommCareCaseIndex( identifier='host', referenced_type='occurrence', referenced_id=occurrence_case.get_id, relationship='extension', ), episode_case.indices[0]) # make sure the case is only created/modified by a single form self.assertEqual(1, len(episode_case.xform_ids))
def indices(self): from casexml.apps.case.sharedmodels import CommCareCaseIndex return [CommCareCaseIndex.wrap(index) for index in self._data['indices']]
def get_reverse_indices(case): return [CommCareCaseIndex.wrap(raw) for raw in get_reverse_indices_json(case)]