def setUp(self): now = datetime.utcnow() owner_id = str(uuid4()) self.parent_case_id = str(uuid4()) self.parent_case = CommCareCase( case_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( case_id=self.child_case_id, domain=DOMAIN, type='vitals', case_json={'temperature': 36.1}, owner_id=owner_id, modified_on=now, server_modified_on=now, ) self.child_case.save() add_case_index( self.child_case, identifier='parent', referenced_type='person', referenced_id=self.parent_case_id, )
class IndexSimpleTest(SimpleTestCase): 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]) def testHasIndex(self): self.assertEqual(True, self.case.has_index('i1')) self.assertEqual(True, self.case.has_index('i2')) self.assertEqual(False, self.case.has_index('i3')) def testGetIndex(self): self.assertEqual(self.i1, self.case.get_index('i1')) self.assertEqual(self.i2, self.case.get_index('i2')) self.assertEqual(None, self.case.get_index('i3')) self.assertEqual(None, self.case.get_index('id1'))
def _test_refer_case_payload_generator(initial_case_properties, expected_referral_props): domain = "source_domain" repeater = ReferCaseRepeater(domain=domain) generator = ReferCasePayloadGenerator(repeater) generator.submission_user_id = Mock(return_value='user1') generator.submission_username = Mock(return_value='user1') transfer_case = CommCareCase(type="transfer", case_json={ "cases_to_forward": "case1", "new_owner": "owner1", "case_types": "patient", "patient_whitelist": "copy_this" }) copy_value = uuid.uuid4().hex properties = {"copy_this": copy_value} properties.update(initial_case_properties or {}) target_case = CommCareCase(case_id="1", type="patient", case_json=properties) with patch.object(CommCareCase.objects, "get_cases", return_value=[target_case]): form = generator.get_payload(None, transfer_case) formxml = ElementTree.fromstring(form) case = CaseBlock.from_xml(formxml.find("{%s}case" % V2_NAMESPACE)) expected_update = { "cchq_referral_source_domain": domain, "cchq_referral_source_case_id": "1", "copy_this": copy_value } expected_update.update(expected_referral_props) eq(case.update, expected_update)
def setUp(self): now = datetime.utcnow() case_kwargs = { 'owner_id': uuid4().hex, 'modified_on': now, 'server_modified_on': now, } self.host_case_id = uuid4().hex case = CommCareCase( case_id=self.host_case_id, domain=self.domain, type='person', name='Ted', **case_kwargs, ) self.host_case = create_case(case) case = CommCareCase( case_id=uuid4().hex, domain=self.domain, type='person_name', name='Theodore', case_json={ 'given_names': 'Theodore John', 'family_name': 'Kaczynski', }, **case_kwargs, ) index = CommCareCaseIndex( domain=self.domain, identifier='host', referenced_type='person', referenced_id=self.host_case_id, relationship_id=CommCareCaseIndex.EXTENSION, ) self.ext_case_1 = create_case_with_index(case, index) case = CommCareCase( case_id=uuid4().hex, domain=self.domain, type='person_name', name='Unabomber', case_json={ 'given_names': 'Unabomber', }, **case_kwargs, ) index = CommCareCaseIndex( domain=self.domain, identifier='host', referenced_type='person', referenced_id=self.host_case_id, relationship_id=CommCareCaseIndex.EXTENSION, ) self.ext_case_2 = create_case_with_index(case, index)
def setUp(self): now = datetime.utcnow() yesterday = now - timedelta(days=1) owner_id = uuid4().hex self.parent_case_id = uuid4().hex case = CommCareCase( case_id=self.parent_case_id, domain=self.domain, type='person', name='Joe', owner_id=owner_id, modified_on=yesterday, server_modified_on=yesterday, ) self.parent_case = create_case(case) case = CommCareCase( case_id=uuid4().hex, domain=self.domain, type='temperature', case_json={ 'value': '36.2', }, owner_id=owner_id, modified_on=yesterday, server_modified_on=yesterday, ) index = CommCareCaseIndex( domain=self.domain, identifier='parent', referenced_type='person', referenced_id=self.parent_case_id, relationship_id=CommCareCaseIndex.CHILD, ) self.child_case_1 = create_case_with_index(case, index) case = CommCareCase( case_id=uuid4().hex, domain=self.domain, type='temperature', case_json={ 'value': '36.6', }, owner_id=owner_id, modified_on=now, server_modified_on=now, ) index = CommCareCaseIndex( domain=self.domain, identifier='parent', referenced_type='person', referenced_id=self.parent_case_id, relationship_id=CommCareCaseIndex.CHILD, ) self.child_case_2 = create_case_with_index(case, index)
def test_get_expanded_case_results(get_cases_mock): cases = [ CommCareCase(case_json={}), CommCareCase(case_json={"potential_duplicate_id": "123"}), CommCareCase(case_json={"potential_duplicate_id": "456"}), CommCareCase(case_json={"potential_duplicate_id": ""}), CommCareCase(case_json={"potential_duplicate_id": None}), ] helper = None get_expanded_case_results(helper, "potential_duplicate_id", cases) get_cases_mock.assert_called_with(helper, {"123", "456"})
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 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()
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
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])
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)
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'], })
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
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'])
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 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' )
def get_case_with_lock(case_id, lock=False, wrap=False): try: if lock: try: return CommCareCase.get_locked_obj(_id=case_id) except redis.RedisError: case = CommCareCase.objects.get_case(case_id) else:
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]
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')
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
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)
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': [], })
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
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
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)
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))
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']
def get_databases(): """Return an ordered dict of (dbname: database). The order is according to search preference, the first DB to contain a document should be assumed to be the authoritative one.""" sql_dbs = [ _SQLDb( XFormInstance._meta.db_table, lambda id_: XFormInstance.get_obj_by_id(id_), "XFormInstance", lambda doc: XFormInstanceRawDocSerializer(doc).data, ), _SQLDb( CommCareCase._meta.db_table, lambda id_: CommCareCase.get_obj_by_id(id_), "CommCareCase", lambda doc: CommCareCaseRawDocSerializer(doc).data, ), _SQLDb( SQLLocation._meta.db_table, lambda id_: SQLLocation.objects.get(location_id=id_), 'Location', lambda doc: doc.to_json() ), _SQLDb( SMS._meta.db_table, lambda id_: SMS.objects.get(couch_id=id_), 'SMS', lambda doc: doc.to_json() ), _SQLDb( SQLMobileBackend._meta.db_table, lambda id_: SQLMobileBackend.objects.get(couch_id=id_), 'SQLMobileBackend', lambda doc: doc.to_json() ), ] all_dbs = OrderedDict() for db in sql_dbs: all_dbs[db.dbname] = db couchdbs_by_name = couch_config.all_dbs_by_db_name for dbname in sorted(couchdbs_by_name): all_dbs[dbname] = _CouchDb(couchdbs_by_name[dbname]) return all_dbs
def setUp(self): now = datetime.utcnow() self.parent_case_id = str(uuid4()) self.parent_case = CommCareCase( case_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', case_json={ 'given_names': 'Theodore John', 'family_name': 'Kaczynski', }, owner_id=str(uuid4()), modified_on=now, server_modified_on=now, ) self.child_case_1.save() add_case_index( self.child_case_1, identifier='parent', referenced_type='person', referenced_id=self.parent_case_id, ) self.child_case_2 = CommCareCase( case_id='222222222', domain=DOMAIN, type='person_name', name='Unabomber', case_json={'given_names': 'Unabomber'}, owner_id=str(uuid4()), modified_on=now, server_modified_on=now, ) self.child_case_2.save() add_case_index( self.child_case_2, identifier='parent', referenced_type='person', referenced_id=self.parent_case_id, )
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' }, )