def test_walk_ids_ignore_related(self):
     case_id = uuid.uuid4().hex
     parent_case_id = uuid.uuid4().hex
     grandparent_case_id = uuid.uuid4().hex
     structure = CaseStructure(
         case_id=case_id,
         relationships=[
             CaseRelationship(CaseStructure(
                 case_id=parent_case_id,
                 relationships=[
                     CaseRelationship(CaseStructure(case_id=grandparent_case_id))
                 ]))
         ]
     )
     structure.walk_related = False
     self.assertEqual(
         [case_id],
         list(structure.walk_ids())
     )
     structure.walk_related = True
     structure.relationships[0].related_structure.walk_related = False
     self.assertEqual(
         [case_id, parent_case_id],
         list(structure.walk_ids())
     )
 def test_walk_ids(self):
     case_id = uuid.uuid4().hex
     parent_case_id = uuid.uuid4().hex
     grandparent_case_id = uuid.uuid4().hex
     structure = CaseStructure(
         case_id=case_id,
         indices=[
             CaseIndex(
                 CaseStructure(
                     case_id=parent_case_id, indices=[CaseIndex(CaseStructure(case_id=grandparent_case_id))]
                 )
             )
         ],
     )
     self.assertEqual([case_id, parent_case_id, grandparent_case_id], list(structure.walk_ids()))
 def test_walk_ids(self):
     case_id = uuid.uuid4().hex
     parent_case_id = uuid.uuid4().hex
     grandparent_case_id = uuid.uuid4().hex
     structure = CaseStructure(
         case_id=case_id,
         relationships=[
             CaseRelationship(CaseStructure(
                 case_id=parent_case_id,
                 relationships=[
                     CaseRelationship(CaseStructure(case_id=grandparent_case_id))
                 ]))
         ]
     )
     self.assertEqual(
         [case_id, parent_case_id, grandparent_case_id],
         list(structure.walk_ids())
     )
Beispiel #4
0
 def testCaseLookupTypeCheck(self):
     [case] = self.factory.create_or_update_case(
         CaseStructure(attrs={
             'create': True,
             'case_type': 'nonmatch-type',
         }))
     self.assertEqual(1, len(self.accessor.get_case_ids_in_domain()))
     config = self._config(self.default_headers)
     file = MockExcelFile(header_columns=self.default_headers,
                          num_rows=3,
                          row_generator=id_match_generator(case.case_id))
     res = do_import(file, config, self.domain)
     # because the type is wrong these shouldn't match
     self.assertEqual(3, res['created_count'])
     self.assertEqual(0, res['match_count'])
     self.assertEqual(4, len(self.accessor.get_case_ids_in_domain()))
Beispiel #5
0
 def lab_referral(self):
     return CaseStructure(
         case_id=self.lab_referral_id,
         attrs={
             'create': True,
             'case_type': 'lab_referral',
             'owner_id': self.dmc.get_id,
             "update": {}
         },
         indices=[CaseIndex(
             self.test,
             identifier='host',
             relationship=CASE_INDEX_EXTENSION,
             related_type=self.test.attrs['case_type'],
         )],
     )
 def test_get_payload(self):
     cases = self.create_case_structure()
     cases[self.episode_id] = self.create_case(
         CaseStructure(case_id=self.episode_id,
                       attrs={
                           "update": {
                               TREATMENT_OUTCOME: 'the_end_of_days',
                               TREATMENT_OUTCOME_DATE: '2017-01-07',
                           },
                       }))[0]
     expected_payload = json.dumps({
         "beneficiary_id": "person",
         "treatment_outcome": "the_end_of_days",
         "end_date": "2017-01-07"
     })
     self.assertEqual(self._get_actual_payload(cases), expected_payload)
Beispiel #7
0
 def person(self):
     return CaseStructure(
         case_id=self.person_id,
         attrs={
             "case_type": "person",
             "create": True,
             "update": dict(
                 name="Pippin",
                 aadhaar_number="499118665246",
                 phone_number="0123456789",
                 backup_number="0999999999",
                 merm_id="123456789",
                 dob="1987-08-15",
             )
         },
     )
    def test_legacy_support_toggle(self):
        restore_config = RestoreConfig(self.project, restore_user=self.user)
        factory = CaseFactory(domain=self.project.name,
                              case_defaults={'owner_id': self.user_id})
        # create a parent and child case (with index) from one user
        parent_id, child_id = [uuid.uuid4().hex for i in range(2)]
        factory.create_or_update_cases([
            CaseStructure(
                case_id=child_id,
                attrs={'create': True},
                indices=[
                    CaseIndex(
                        CaseStructure(case_id=parent_id,
                                      attrs={'create': True}),
                        relationship='child',
                        related_type='parent',
                    )
                ],
            )
        ])
        restore_payload = restore_config.get_payload().as_string()
        self.assertTrue(child_id in restore_payload)
        self.assertTrue(parent_id in restore_payload)
        sync_log = deprecated_synclog_from_restore_payload(restore_payload)
        self.assertEqual(SimplifiedSyncLog, type(sync_log))
        # make both cases irrelevant by changing the owner ids
        factory.create_or_update_cases([
            CaseStructure(case_id=parent_id, attrs={'owner_id': 'different'}),
            CaseStructure(case_id=child_id, attrs={'owner_id': 'different'}),
        ],
                                       form_extras={
                                           'last_sync_token': sync_log._id
                                       })

        # doing it again should fail since they are no longer relevant

        # todo: add this back in when we add the assertion back. see SimplifiedSyncLog.prune_case
        # with self.assertRaises(SimplifiedSyncAssertionError):
        #     factory.create_or_update_cases([
        #         CaseStructure(case_id=child_id, attrs={'owner_id': 'different'}),
        #         CaseStructure(case_id=parent_id, attrs={'owner_id': 'different'}),
        #     ], form_extras={'last_sync_token': sync_log._id})

        # enabling the toggle should prevent the failure the second time
        # though we also need to hackily set the request object in the threadlocals
        LEGACY_SYNC_SUPPORT.set(self.domain, True, namespace='domain')
        request = JsonObject(domain=self.domain, path='testsubmit')
        set_request(request)
        factory.create_or_update_cases([
            CaseStructure(case_id=child_id, attrs={'owner_id': 'different'}),
            CaseStructure(case_id=parent_id, attrs={'owner_id': 'different'}),
        ],
                                       form_extras={
                                           'last_sync_token': sync_log._id
                                       })
Beispiel #9
0
 def test_handle_success(self):
     cases = self.create_case_structure()
     self.factory.create_or_update_case(CaseStructure(
         case_id=self.episode_id,
         attrs={
             'create': False,
             'update': {'dots_99_error': 'bad things'},
         },
     ))
     payload_generator = UpdatePatientPayloadGenerator(None)
     payload_generator.handle_success(MockResponse(200, {"success": "hooray"}), cases[self.person_id], None)
     updated_episode_case = CaseAccessors(self.domain).get_case(self.episode_id)
     self.assertEqual(
         updated_episode_case.dynamic_case_properties().get('dots_99_error'),
         ''
     )
Beispiel #10
0
 def person(self):
     return CaseStructure(
         case_id=self.person_id,
         attrs={
             "case_type": "person",
             "create": True,
             "update": {
                 'name': "Pippin",
                 'aadhaar_number': "499118665246",
                 PRIMARY_PHONE_NUMBER: self.primary_phone_number,
                 BACKUP_PHONE_NUMBER: self.secondary_phone_number,
                 'merm_id': "123456789",
                 'dob': "1987-08-15",
             }
         },
     )
Beispiel #11
0
 def test_call_center_not_default_case_owner(self):
     """
     call center case owner should not change on sync
     """
     factory = CaseFactory(domain=TEST_DOMAIN, case_defaults={
         'user_id': self.user_id,
         'owner_id': 'another_user',
         'case_type': CASE_TYPE,
         'update': {'hq_user_id': self.user_id}
     })
     cases = factory.create_or_update_cases([
         CaseStructure(attrs={'create': True})
     ])
     sync_call_center_user_case(self.user)
     case = self._get_user_case()
     self.assertEqual(case.owner_id, cases[0].owner_id)
    def test_close_cases_host(self):
        """Closing a host should close all the extensions"""
        self._create_extension_chain()
        cases = CaseAccessors(self.domain).get_cases(self.extension_ids)
        self.assertFalse(cases[0].closed)
        self.assertFalse(cases[1].closed)
        self.assertFalse(cases[2].closed)

        self.factory.create_or_update_case(CaseStructure(
            case_id=self.extension_ids[1],
            attrs={'close': True}
        ))
        cases = {
            case.case_id: case.closed
            for case in CaseAccessors(self.domain).get_cases([self.host_id] + self.extension_ids)
        }
Beispiel #13
0
 def occurrence(self):
     return CaseStructure(
         case_id=self.occurrence_id,
         attrs={
             'create': True,
             'case_type': 'occurrence',
             "update": dict(
                 name="Occurrence #1",
             )
         },
         indices=[CaseIndex(
             self.person,
             identifier='host',
             relationship=CASE_INDEX_EXTENSION,
             related_type=self.person.attrs['case_type'],
         )],
     )
Beispiel #14
0
    def test_reprocess_unfinished_submission_ledger_create(self):
        from corehq.apps.commtrack.tests.util import get_single_balance_block
        case_id = uuid.uuid4().hex
        self.factory.create_or_update_cases([
            CaseStructure(case_id=case_id,
                          attrs={
                              'case_type': 'parent',
                              'create': True
                          })
        ])

        with _patch_save_to_raise_error(self):
            submit_case_blocks(
                get_single_balance_block(case_id, 'product1', 100),
                self.domain)

        stubs = UnfinishedSubmissionStub.objects.filter(domain=self.domain,
                                                        saved=False).all()
        self.assertEqual(1, len(stubs))

        ledgers = self.ledgerdb.get_ledger_values_for_case(case_id)
        self.assertEqual(0, len(ledgers))

        case = self.casedb.get_case(case_id)
        self.assertEqual(1, len(case.xform_ids))

        ledger_transactions = self.ledgerdb.get_ledger_transactions_for_case(
            case_id)
        self.assertEqual(0, len(ledger_transactions))

        result = reprocess_unfinished_stub(stubs[0])
        self.assertEqual(1, len(result.cases))
        self.assertEqual(1, len(result.ledgers))

        ledgers = self.ledgerdb.get_ledger_values_for_case(case_id)
        self.assertEqual(1, len(ledgers))

        ledger_transactions = self.ledgerdb.get_ledger_transactions_for_case(
            case_id)
        self.assertEqual(1, len(ledger_transactions))

        # case still only has 2 transactions
        case = self.casedb.get_case(case_id)
        self.assertEqual(2, len(case.xform_ids))
        if should_use_sql_backend(self.domain):
            self.assertTrue(case.actions[1].is_ledger_transaction)
Beispiel #15
0
    def testParentCase(self):
        headers = ['parent_id', 'name', 'case_id']
        config = self._config(headers,
                              create_new_cases=True,
                              search_column='case_id')
        rows = 3
        [parent_case] = self.factory.create_or_update_case(
            CaseStructure(attrs={'create': True}))
        self.assertEqual(
            1, len(CommCareCase.objects.get_case_ids_in_domain(self.domain)))

        file = make_worksheet_wrapper(
            ['parent_id', 'name', 'case_id'],
            [parent_case.case_id, 'name-0', 'case_id-0'],
            [parent_case.case_id, 'name-1', 'case_id-1'],
            [parent_case.case_id, 'name-2', 'case_id-2'],
        )

        # Should successfully match on `rows` cases
        res = do_import(file, config, self.domain)
        self.assertEqual(rows, res['created_count'])
        # Should create child cases
        cases = CommCareCase.objects.get_reverse_indexed_cases(
            self.domain, [parent_case.case_id])
        self.assertEqual(len(cases), 3)
        self.assertEqual(
            CommCareCaseIndex.objects.get_extension_case_ids(
                self.domain, [parent_case.case_id]),
            [],
        )

        file_missing = make_worksheet_wrapper(
            ['parent_id', 'name', 'case_id'],
            ['parent_id-0', 'name-0', 'case_id-0'],
            ['parent_id-1', 'name-1', 'case_id-1'],
            ['parent_id-2', 'name-2', 'case_id-2'],
        )

        # Should be unable to find parent case on `rows` cases
        res = do_import(file_missing, config, self.domain)
        error_column_name = 'parent_id'
        self.assertEqual(
            rows,
            len(res['errors'][exceptions.InvalidParentId.title]
                [error_column_name]['rows']),
            "All cases should have missing parent")
Beispiel #16
0
    def handle(self, domain, log_path, **options):
        commit = options['commit']
        factory = CaseFactory(domain)

        logger.info("Starting {} migration on {} at {}".format(
            "real" if commit else "fake", domain, datetime.datetime.utcnow()))

        cases = (CaseSearchES().domain(domain).case_type(
            "episode").case_property_query("case_version", "20",
                                           "must").scroll())

        with open(log_path, "w") as f:
            for case in cases:
                case_props = {
                    prop['key']: prop['value']
                    for prop in case['case_properties']
                }
                referred_by_id = case_props.get('referred_by_id')
                updated_by_migration = case_props.get('updated_by_migration')
                if ((updated_by_migration == 'enikshay_2b_case_properties'
                     or updated_by_migration
                     == 'enikshay_2b_treatment_status_fix')
                        and referred_by_id):

                    case_id = case['_id']
                    f.write(case_id + "\n")
                    logger.info(case_id)

                    case_structure = CaseStructure(
                        case_id=case_id,
                        walk_related=False,
                        attrs={
                            "create": False,
                            "update": {
                                "referred_outside_enikshay_by_id":
                                referred_by_id,
                                "updated_by_migration":
                                "enikshay_2b_referred_by_id_fix",
                            },
                        },
                    )

                    if commit:
                        factory.create_or_update_case(case_structure)
        logger.info("Migration finished at {}".format(
            datetime.datetime.utcnow()))
Beispiel #17
0
def get_occurrence_case_structure(case_id, indexed_person_case):
    return CaseStructure(
        case_id=case_id,
        attrs={
            'create': True,
            'case_type': 'occurrence',
            "update": dict(name="Occurrence #1", )
        },
        indices=[
            CaseIndex(
                indexed_person_case,
                identifier='host',
                relationship=CASE_INDEX_EXTENSION,
                related_type=indexed_person_case.attrs['case_type'],
            )
        ],
    )
    def migrate_episode(self, episode, episodes):
        self.total_episodes += 1

        latest_episode_id = self._get_last_episode_id(episode.indices, episodes)
        test_type = episode.get_case_property('test_confirming_diagnosis')
        props = {
            'updated_by_migration': 'enikshay_2b_case_properties',
            'is_active': 'yes' if episode.case_id == latest_episode_id and not episode.closed else 'no',
            'dosage_display': episode.get_case_property('full_dosage'),
            'dosage_summary': episode.get_case_property('full_dosage'),
            'rft_general': 'diagnosis_dstb',
            'diagnosis_test_type': test_type,
            'diagnosis_test_type_label': TEST_TO_LABEL.get(test_type, ""),
        }

        treatment_status = episode.get_case_property('treatment_status')
        treatment_initiated = episode.get_case_property('treatment_initiated')
        diagnosing_facility_id = episode.get_case_property('diagnosing_facility_id')
        treatment_initiating_facility_id = episode.get_case_property('treatment_initiating_facility_id')
        if treatment_status == 'second_line_treatment':
            props['treatment_status'] = 'initiated_second_line_treatment'
        # skipping patients who don't have a diagnosing and treatment IDs (so we don't set the wrong status)
        elif treatment_initiated == 'yes_phi' and diagnosing_facility_id and treatment_initiating_facility_id \
                and diagnosing_facility_id != treatment_initiating_facility_id:
            props['treatment_status'] = 'initiated_outside_facility'
        # skipping patients who don't have a diagnosing and treatment IDs (so we don't set the wrong status)
        elif treatment_initiated == 'yes_phi' and diagnosing_facility_id and treatment_initiating_facility_id:
            props['treatment_status'] = 'initiated_first_line_treatment'
        elif treatment_initiated == 'yes_private':
            props['treatment_status'] = 'initiated_outside_rntcp'

        if treatment_status and treatment_status != 'yes_phi' and treatment_status != 'yes_private':
            props['treatment_initiated'] = 'no'

        if not episode.get_case_property('date_of_diagnosis'):
            props['date_of_diagnosis'] = episode.get_case_property('date_reported')

        return CaseStructure(
            case_id=episode.case_id,
            walk_related=False,
            attrs={
                "create": False,
                "update": props,
            },
        )
Beispiel #19
0
 def testCaseLookupTypeCheck(self):
     [case] = self.factory.create_or_update_case(CaseStructure(attrs={
         'create': True,
         'case_type': 'nonmatch-type',
     }))
     self.assertEqual(1, len(self.accessor.get_case_ids_in_domain()))
     config = self._config(['case_id', 'age', 'sex', 'location'])
     file = make_worksheet_wrapper(
         ['case_id', 'age', 'sex', 'location'],
         [case.case_id, 'age-0', 'sex-0', 'location-0'],
         [case.case_id, 'age-1', 'sex-1', 'location-1'],
         [case.case_id, 'age-2', 'sex-2', 'location-2'],
     )
     res = do_import(file, config, self.domain)
     # because the type is wrong these shouldn't match
     self.assertEqual(3, res['created_count'])
     self.assertEqual(0, res['match_count'])
     self.assertEqual(4, len(self.accessor.get_case_ids_in_domain()))
 def test_prevention_of_update_chaining(self):
     builder = (IntentCaseBuilder(self.registry_slug).target_case(
         self.target_domain,
         self.target_case_id_1).case_properties(new_prop="new_val_case1"))
     case = CaseStructure(attrs={
         "create": True,
         "case_type": "registry_case_update",
         "update": builder.props
     }, )
     CaseFactory(self.domain).create_or_update_case(
         case,
         user_id=self.mobile_user.get_id,
         form_extras={
             # pretend this form came from a repeater in another domain
             'xmlns': DataRegistryCaseUpdatePayloadGenerator.XMLNS
         })
     repeat_records = self.repeat_records(self.domain).all()
     self.assertEqual(len(repeat_records), 0)
Beispiel #21
0
def get_episode_case_structure(case_id,
                               indexed_occurrence_case,
                               extra_update=None):
    extra_update = extra_update or {}
    update = {
        'date_of_diagnosis': '2014-09-09',
        'default_adherence_confidence': 'high',
        'disease_classification': 'extra_pulmonary',
        'episode_type': 'confirmed_tb',
        'hiv_status': 'reactive',
        'name': 'Episode #1',
        'occupation': 'engineer',
        'opened_on': datetime(1989, 6, 11, 0, 0),
        'patient_type_choice': 'treatment_after_lfu',
        'person_name': u'Peregrine เՇร ค Շгคק',
        'site_choice': 'pleural_effusion',
        'treatment_supporter_designation': 'ngo_volunteer',
        'treatment_initiated': TREATMENT_INITIATED_IN_PHI,
        TREATMENT_START_DATE: "2015-03-03",
        TREATMENT_SUPPORTER_FIRST_NAME: u"𝔊𝔞𝔫𝔡𝔞𝔩𝔣",
        TREATMENT_SUPPORTER_LAST_NAME: u"𝔗𝔥𝔢 𝔊𝔯𝔢𝔶",
        MERM_ID: "123456789",
        'treatment_initiation_status': 'F',
        'dst_status': 'pending',
        'basis_of_diagnosis': 'clinical_other',
    }
    update.update(extra_update)

    return CaseStructure(
        case_id=case_id,
        attrs={
            'create': True,
            'case_type': 'episode',
            "update": update
        },
        indices=[
            CaseIndex(
                indexed_occurrence_case,
                identifier='host',
                relationship=CASE_INDEX_EXTENSION,
                related_type=indexed_occurrence_case.attrs['case_type'],
            )
        ],
    )
Beispiel #22
0
 def test_walk_ids_ignore_related(self):
     case_id = uuid.uuid4().hex
     parent_case_id = uuid.uuid4().hex
     grandparent_case_id = uuid.uuid4().hex
     structure = CaseStructure(
         case_id=case_id,
         indices=[
             CaseIndex(
                 CaseStructure(
                     case_id=parent_case_id,
                     indices=[
                         CaseIndex(
                             CaseStructure(case_id=grandparent_case_id))
                     ]))
         ])
     structure.walk_related = False
     self.assertEqual([case_id], list(structure.walk_ids()))
     structure.walk_related = True
     structure.indices[0].related_structure.walk_related = False
     self.assertEqual([case_id, parent_case_id], list(structure.walk_ids()))
    def test_get_extension_to_close(self):
        """should return empty if case is not a host, otherwise should return full chain"""
        created_cases = self._create_extension_chain()
        # host open, should be empty
        no_cases = get_extensions_to_close(created_cases[-1], self.domain)
        self.assertEqual(set(), no_cases)

        created_cases[-1] = self.factory.create_or_update_case(CaseStructure(
            case_id=self.host_id,
            attrs={'close': True}
        ))[0]

        # host closed, should get full chain
        full_chain = get_extensions_to_close(created_cases[-1], self.domain)
        self.assertEqual(set(self.extension_ids), full_chain)

        # extension (not a host), should be empty
        no_cases = get_extensions_to_close(created_cases[2], self.domain)
        self.assertEqual(set(), no_cases)
Beispiel #24
0
 def get_test_case_structure(self, labtest, occurrence_structure):
     kwargs = {
         'attrs': {
             'case_type': TEST_CASE_TYPE,
             'close': False,
             'create': True,
             'owner_id': '-',
             'update': {
                 'migration_created_case': 'true',
             }
         },
         'indices': [CaseIndex(
             occurrence_structure,
             identifier='host',
             relationship=CASE_INDEX_EXTENSION,
             related_type=OCCURRENCE_CASE_TYPE,
         )],
     }
     return CaseStructure(**kwargs)
    def migrate_referral(self, referral, occurrence):
        self.total_referrals += 1
        prop = referral.get_case_property
        props = {
            'updated_by_migration':
            'enikshay_2b_case_properties',
            'referral_initiated_date': (prop('referral_date')
                                        or prop('date_of_referral')),
            'referred_to_name':
            prop('referred_to_location_name'),
            'referred_by_name':
            prop('referred_by'),
            'referral_rejection_reason_other_detail':
            prop('reason_for_refusal_other_detail'),
            'referral_rejection_reason':
            prop('reason_for_refusal'),
            'referral_closed_date':
            prop('acceptance_refusal_date'),
            'accepted_by_name':
            prop('phi'),
        }

        if occurrence:
            index_kwargs = {
                'indices': [
                    CaseIndex(
                        occurrence,
                        identifier='host',
                        relationship=CASE_INDEX_EXTENSION,
                        related_type=CASE_TYPE_OCCURRENCE,
                    )
                ]
            }
        else:
            index_kwargs = {}

        return CaseStructure(case_id=referral.case_id,
                             walk_related=False,
                             attrs={
                                 "create": False,
                                 "update": props,
                             },
                             **index_kwargs)
    def handle(self, domain, log_path, **options):
        commit = options['commit']
        factory = CaseFactory(domain)

        logger.info("Starting {} migration on {} at {}".format(
            "real" if commit else "fake", domain, datetime.datetime.utcnow()))

        cases = (CaseSearchES().domain(domain).case_type(
            "test").case_property_query("updated_by_migration",
                                        "enikshay_2b_case_properties",
                                        "must").run().hits)

        with open(log_path, "w") as f:
            for case in cases:
                case_props = {
                    prop['key']: prop['value']
                    for prop in case['case_properties']
                }
                if (case_props.get('purpose_of_testing') == "follow_up_dstb"
                        and case_props.get("rft_general", "") in ("", None)):
                    case_id = case['_id']
                    f.write(case_id + "\n")
                    logger.info(case_id)

                    case_structure = CaseStructure(
                        case_id=case_id,
                        walk_related=False,
                        attrs={
                            "create": False,
                            "update": {
                                "rft_general":
                                "follow_up_dstb",
                                "updated_by_migration":
                                "enikshay_2b_reason_for_test_fix",
                            },
                        },
                    )

                    if commit:
                        factory.create_or_update_case(case_structure)

        logger.info("Migration finished at {}".format(
            datetime.datetime.utcnow()))
    def test_reprocess_unfinished_submission_case_create(self):
        case_id = uuid.uuid4().hex
        with _patch_save_to_raise_error(self):
            self.factory.create_or_update_cases([
                CaseStructure(case_id=case_id,
                              attrs={
                                  'case_type': 'parent',
                                  'create': True
                              })
            ])

        stubs = UnfinishedSubmissionStub.objects.filter(domain=self.domain,
                                                        saved=False).all()
        self.assertEqual(1, len(stubs))

        # form that was saved before case error raised
        normal_form_ids = XFormInstance.objects.get_form_ids_in_domain(
            self.domain, 'XFormInstance')
        self.assertEqual(0, len(normal_form_ids))

        # shows error form (duplicate of form that was saved before case error)
        # this is saved becuase the saving was assumed to be atomic so if there was any error it's assumed
        # the form didn't get saved
        # we don't really care about this form in this test
        error_forms = XFormInstance.objects.get_forms_by_type(
            self.domain, 'XFormError', 10)
        self.assertEqual(1, len(error_forms))
        self.assertIsNone(error_forms[0].orig_id)
        self.assertEqual(error_forms[0].form_id, stubs[0].xform_id)

        self.assertEqual(
            0, len(CommCareCase.objects.get_case_ids_in_domain(self.domain)))

        result = reprocess_unfinished_stub(stubs[0])
        self.assertEqual(1, len(result.cases))

        case_ids = CommCareCase.objects.get_case_ids_in_domain(self.domain)
        self.assertEqual(1, len(case_ids))
        self.assertEqual(case_id, case_ids[0])

        with self.assertRaises(UnfinishedSubmissionStub.DoesNotExist):
            UnfinishedSubmissionStub.objects.get(pk=stubs[0].pk)
Beispiel #28
0
    def get_occurrence_case_structure(self, person_structure):
        """
        This gets the occurrence case structure with a nested person case structure.
        """
        kwargs = {
            'attrs': {
                'case_type': OCCURRENCE_CASE_TYPE,
                'owner_id': '-',
                'update': {
                    'current_episode_type': 'confirmed_tb',
                    'ihv_date': self.patient_detail.ihv_date,
                    'initial_home_visit_status':
                    self.patient_detail.initial_home_visit_status,
                    'name': 'Occurrence #1',
                    'occurrence_episode_count': 1,
                    'occurrence_id': get_human_friendly_id(),
                    'migration_created_case': 'true',
                    'migration_created_from_record':
                    self.patient_detail.PregId,
                },
            },
            'indices': [
                CaseIndex(
                    person_structure,
                    identifier='host',
                    relationship=CASE_INDEX_EXTENSION,
                    related_type=PERSON_CASE_TYPE,
                )
            ],
        }

        if self._outcome:
            if self._outcome.is_treatment_ended:
                kwargs['attrs']['close'] = True

        if self.existing_occurrence_case:
            kwargs['case_id'] = self.existing_occurrence_case.case_id
            kwargs['attrs']['create'] = False
        else:
            kwargs['attrs']['create'] = True

        return CaseStructure(**kwargs)
Beispiel #29
0
class GetDependentCasesTest(TestCase):
    @classmethod
    def setUpClass(cls):
        super(GetDependentCasesTest, cls).setUpClass()
        delete_all_cases()

    def setUp(self):
        super(GetDependentCasesTest, self).setUp()
        self.domain = 'domain'
        self.owner_id = uuid.uuid4().hex
        self.other_owner_id = uuid.uuid4().hex
        self.factory = CaseFactory(self.domain)

    @run_with_all_backends
    def test_returns_nothing_with_no_dependencies(self):
        case = CaseStructure()
        self.factory.create_or_update_case(case)
        self.assertEqual(
            set(),
            get_dependent_case_info(self.domain, [case.case_id]).all_ids)
Beispiel #30
0
 def _case_structure(name, parent, case_type):
     if parent:
         indices = [CaseIndex(
             parent,
             identifier='parent',
             relationship=CASE_INDEX_CHILD,
             related_type=parent.attrs['case_type'],
         )]
     else:
         indices = []
     return CaseStructure(
         case_id=uuid.uuid4().hex,
         attrs={
             "case_type": case_type,
             "create": True,
             "update": {"name": name},
         },
         indices=indices,
         walk_related=True,
     )
Beispiel #31
0
 def setUp(self):
     super(TestGetCaseFormsExpressionTest, self).setUp()
     self.domain = uuid.uuid4().hex
     factory = CaseFactory(domain=self.domain)
     self.test_case_id = uuid.uuid4().hex
     factory.create_or_update_case(CaseStructure(
         case_id=self.test_case_id,
         attrs={
             'case_type': 'test',
             'create': True,
             'date_opened': datetime(2015, 1, 10),
             'date_modified': datetime(2015, 3, 10),
         },
     ))
     self._submit_form(form_date=datetime(2015, 1, 10), case_id=self.test_case_id, xmlns="xmlns_a", foo="a")
     self._submit_form(form_date=datetime(2015, 1, 11), case_id=self.test_case_id, xmlns="xmlns_a", foo="a")
     self._submit_form(form_date=datetime(2015, 2, 3), case_id=self.test_case_id, xmlns="xmlns_b", foo="b")
     self._submit_form(form_date=datetime(2015, 3, 3), case_id=self.test_case_id, xmlns="xmlns_b", foo="b")
     self._submit_form(form_date=datetime(2015, 3, 4), case_id=self.test_case_id, xmlns="xmlns_b", foo="b")
     self._submit_form(form_date=datetime(2015, 3, 5), case_id=self.test_case_id, xmlns="xmlns_c", foo="b")
    def open_secondary_owners(self, drtb_hiv, person, occurrences):
        if not occurrences:
            return None

        self.total_secondary_owners += 1

        occurrence = max((case.opened_on, case) for case in occurrences)[1]
        index_kwargs = {
            'indices': [
                CaseIndex(
                    occurrence,
                    identifier='host',
                    relationship=CASE_INDEX_EXTENSION,
                    related_type=CASE_TYPE_OCCURRENCE,
                )
            ]
        }

        location = self.locations.get(person.owner_id)
        props = {
            'updated_by_migration': 'enikshay_2b_case_properties',
            'secondary_owner_type': 'drtb-hiv',
            'secondary_owner_name': location.name if location else "",
        }

        return CaseStructure(case_id=uuid.uuid4().hex,
                             walk_related=False,
                             attrs={
                                 'create':
                                 True,
                                 'case_type':
                                 CASE_TYPE_SECONDARY_OWNER,
                                 'owner_id':
                                 drtb_hiv.owner_id,
                                 'case_name':
                                 person.get_case_property('person_id') +
                                 "-drtb-hiv",
                                 'update':
                                 props,
                             },
                             **index_kwargs)
    def test_processing_retuns_error_for_missing_form(self):
        case_id = uuid.uuid4().hex
        with _patch_save_to_raise_error(self):
            self.factory.create_or_update_cases([
                CaseStructure(case_id=case_id,
                              attrs={
                                  'case_type': 'parent',
                                  'create': True
                              })
            ])

        stubs = UnfinishedSubmissionStub.objects.filter(domain=self.domain,
                                                        saved=False).all()
        self.assertEqual(1, len(stubs))

        FormProcessorTestUtils.delete_all_cases_forms_ledgers(self.domain)
        with self.assertRaises(XFormNotFound):
            self.formdb.get_form(stubs[0].xform_id)

        result = reprocess_unfinished_stub(stubs[0])
        self.assertIsNotNone(result.error)