def test_parent_child(self):
        parent_id = uuid.uuid4().hex
        parent_type = 'exploder-parent-type'
        parent_block = CaseBlock.deprecated_init(
            create=True,
            case_id=parent_id,
            user_id=self.user_id,
            owner_id=self.user_id,
            case_type=parent_type,
        ).as_text()

        child_id = uuid.uuid4().hex
        child_block = CaseBlock.deprecated_init(
            create=True,
            case_id=child_id,
            user_id=self.user_id,
            owner_id=self.user_id,
            case_type='exploder-child-type',
            index={
                'parent': (parent_type, parent_id)
            },
        ).as_text()

        submit_case_blocks([parent_block, child_block], self.domain.name)
        self.assertEqual(2, len(self.accessor.get_case_ids_in_domain()))

        explode_cases(self.domain.name, self.user_id, 5)
        case_ids = self.accessor.get_case_ids_in_domain()
        cases_back = list(self.accessor.iter_cases(case_ids))
        self.assertEqual(10, len(cases_back))
        parent_cases = {
            p.case_id: p
            for p in [case for case in cases_back if case.type == parent_type]
        }
示例#2
0
    def testMismatch(self):
        sync = self.device.last_sync
        self.assertEqual(CaseStateHash(EMPTY_HASH), sync.log.get_state_hash())

        c1 = CaseBlock.deprecated_init(case_id="abc123",
                                       create=True,
                                       owner_id=self.user.user_id)
        c2 = CaseBlock.deprecated_init(case_id="123abc",
                                       create=True,
                                       owner_id=self.user.user_id)
        self.device.post_changes([c1, c2])

        real_hash = CaseStateHash("409c5c597fa2c2a693b769f0d2ad432b")
        bad_hash = CaseStateHash("thisisntright")
        self.assertEqual(real_hash, sync.get_log().get_state_hash())
        self.device.sync(state_hash=str(real_hash))

        self.device.last_sync = sync
        try:
            self.device.sync(state_hash=str(bad_hash))
        except BadStateException as e:
            self.assertEqual(real_hash, e.server_hash)
            self.assertEqual(bad_hash, e.phone_hash)
            self.assertEqual(set(e.case_ids), {"abc123", "123abc"})
        else:
            self.fail(
                "Call to generate a payload with a bad hash should fail!")
示例#3
0
    def test_case_block_ordering(self):
        case_id1 = uuid.uuid4().hex
        case_id2 = uuid.uuid4().hex
        # updates before create and case blocks for different cases interleaved
        blocks = [
            CaseBlock.deprecated_init(create=False,
                                      case_id=case_id1,
                                      update={
                                          'p': '2'
                                      }).as_xml(),
            CaseBlock.deprecated_init(create=False,
                                      case_id=case_id2,
                                      update={
                                          'p': '2'
                                      }).as_xml(),
            CaseBlock.deprecated_init(create=True,
                                      case_id=case_id1,
                                      update={
                                          'p': '1'
                                      }).as_xml(),
            CaseBlock.deprecated_init(create=True,
                                      case_id=case_id2,
                                      update={
                                          'p': '1'
                                      }).as_xml()
        ]

        xform, cases = post_case_blocks(blocks)
        self.assertEqual(cases[0].get_case_property('p'), '2')
        self.assertEqual(cases[1].get_case_property('p'), '2')
    def setUpClass(cls):
        super().setUpClass()
        case_block = CaseBlock.deprecated_init(
            case_id=CASE_ID,
            create=True,
            case_type="repeater_case",
            case_name="ABC 123",
        ).as_text()

        update_case_block = CaseBlock.deprecated_init(
            case_id=CASE_ID,
            create=False,
            case_name="ABC 234",
        ).as_text()

        cls.instance_id = uuid.uuid4().hex
        cls.xform_xml = XFORM_XML_TEMPLATE.format(
            "https://www.commcarehq.org/test/repeater/", USER_ID,
            cls.instance_id, case_block)
        cls.update_xform_xml = XFORM_XML_TEMPLATE.format(
            "https://www.commcarehq.org/test/repeater/",
            USER_ID,
            uuid.uuid4().hex,
            update_case_block,
        )

        cls.domain_obj = create_domain(cls.domain)

        # DATA_FORWARDING is on PRO and above
        cls.setup_subscription(cls.domain, SoftwarePlanEdition.PRO)
示例#5
0
    def test_missing_transactions(self):
        # this could happen if a form was edited and resulted in a new case transaction
        # e.g. a condition on a case transaction changed
        case_id1 = uuid.uuid4().hex
        case_id2 = uuid.uuid4().hex
        form_id = uuid.uuid4().hex
        case_block = CaseBlock.deprecated_init(
            case_id=case_id1,
            create=True,
        ).as_text()
        submit_case_blocks(case_block, 'test-transactions', form_id=form_id)
        with self.assertRaises(CaseNotFound):
            CaseAccessors().get_case(case_id2)

        # form with same ID submitted but now has a new case transaction
        new_case_block = CaseBlock.deprecated_init(
            case_id=case_id2,
            create=True,
            case_type='t1',
        ).as_text()
        submit_case_blocks([case_block, new_case_block],
                           'test-transactions',
                           form_id=form_id)
        case2 = CaseAccessors().get_case(case_id2)
        self.assertEqual([form_id], case2.xform_ids)
        self.assertEqual('t1', case2.type)
示例#6
0
    def test_error_saving_case_during_edit(self):
        form_id = uuid.uuid4().hex
        case_id = uuid.uuid4().hex
        submit_case_blocks([
            CaseBlock.deprecated_init(case_id=case_id, update={
                'a': "1"
            }).as_text()
        ],
                           self.domain,
                           form_id=form_id)

        with patch(
                'corehq.form_processor.backends.sql.dbaccessors.CaseAccessorSQL.save_case',
                side_effect=IntegrityError), self.assertRaises(IntegrityError):
            submit_case_blocks([
                CaseBlock.deprecated_init(case_id=case_id, update={
                    'a': "2"
                }).as_text()
            ],
                               self.domain,
                               form_id=form_id)

        [error_form_id] = FormAccessorSQL.get_form_ids_in_domain_by_type(
            self.domain, 'XFormError')
        self.assertNotEqual(error_form_id, form_id)
        form = FormAccessorSQL.get_form(error_form_id)
        self.assertTrue(form.is_error)
        self.assertIsNotNone(form.get_xml())
示例#7
0
    def test_submit_to_deleted_case(self):
        """submitting to a deleted case should succeed and affect the case"""
        case_id = uuid.uuid4().hex
        xform, [case] = post_case_blocks([
            CaseBlock.deprecated_init(create=True,
                                      case_id=case_id,
                                      user_id='whatever',
                                      update={
                                          'foo': 'bar'
                                      }).as_xml()
        ],
                                         domain="test-domain")
        cases = CaseAccessors("test-domain")
        cases.soft_delete_cases([case_id])

        case = cases.get_case(case_id)
        self.assertEqual('bar', case.dynamic_case_properties()['foo'])
        self.assertTrue(case.is_deleted)

        xform, [case] = post_case_blocks([
            CaseBlock.deprecated_init(create=False,
                                      case_id=case_id,
                                      user_id='whatever',
                                      update={
                                          'foo': 'not_bar'
                                      }).as_xml()
        ])
        self.assertEqual('not_bar', case.dynamic_case_properties()['foo'])
        self.assertTrue(case.is_deleted)
 def test_does_not_let_you_specify_a_keyword_twice(self):
     """Doesn't let you specify a keyword twice (here 'case_name')"""
     with self.assertRaises(CaseBlockError) as context:
         CaseBlock.deprecated_init(
             case_id=self.CASE_ID,
             case_name='Johnny',
             update={'case_name': 'Johnny'},
         ).as_xml()
     self.assertEqual(six.text_type(context.exception), "Key 'case_name' specified twice")
    def setUpClass(cls):
        super(TestFormProcessorCouch, cls).setUpClass()
        cls.case_id = uuid.uuid4().hex
        case = CaseBlock.deprecated_init(create=True,
                                         case_id=cls.case_id,
                                         user_id='user1',
                                         owner_id='user1',
                                         case_type='demo',
                                         case_name='wrap?')
        cls.domain = uuid.uuid4().hex

        cls.case = post_case_blocks([case.as_xml()], domain=cls.domain)[1][0]
 def _submit_form(self, domain, new_cases=0, update_cases=()):
     case_blocks = [
         CaseBlock.deprecated_init(
             case_id=str(uuid.uuid4()),
             case_type=self.case_type,
             create={'name': str(uuid.uuid4())[:5]},
         ) for i in range(new_cases)
     ]
     case_blocks += [
         CaseBlock.deprecated_init(case_id=case.case_id, update={})
         for case in update_cases
     ]
示例#11
0
    def test_async_invalid_data(self):
        # re-fetch from DB to bust object caches
        self.config = DataSourceConfiguration.get(self.config.data_source_id)

        self.config.validations = [
            Validation.wrap({
                "name": "impossible_condition",
                "error_message": "This condition is impossible to satisfy",
                "expression": {
                    "type": "boolean_expression",
                    "expression": {
                        "type": "property_name",
                        "property_name": "doesnt_exist"
                    },
                    "operator": "in",
                    "property_value": ["nonsense"]
                }
            })
        ]

        self.config.save()
        parent_id, child_id = uuid.uuid4().hex, uuid.uuid4().hex
        since = self.pillow.get_change_feed().get_latest_offsets()
        for i in range(3):
            form, cases = post_case_blocks([
                CaseBlock.deprecated_init(
                    create=i == 0,
                    case_id=parent_id,
                    case_name='parent-name',
                    case_type='bug',
                    update={
                        'update-prop-parent': i
                    },
                ).as_xml(),
                CaseBlock.deprecated_init(create=i == 0,
                                          case_id=child_id,
                                          case_name='child-name',
                                          case_type='bug-child',
                                          index={
                                              'parent': ('bug', parent_id)
                                          },
                                          update={
                                              'update-prop-child': i
                                          }).as_xml()
            ],
                                           domain=self.domain)
        self.pillow.process_changes(since=since, forever=False)

        # run async queue
        queue_async_indicators()
        self.assertEqual(InvalidUCRData.objects.count(), 1)
示例#12
0
    def test_processing_error(self):
        case_id = uuid.uuid4().hex
        parent_case_id = uuid.uuid4().hex
        form_id = uuid.uuid4().hex
        form, _ = submit_case_blocks(CaseBlock.deprecated_init(
            case_id=case_id,
            create=True,
            case_type='box',
            index={
                'cupboard': ('cupboard', parent_case_id)
            },
        ).as_text(),
                                     self.domain,
                                     form_id=form_id)

        self.assertTrue(form.is_error)
        self.assertTrue('InvalidCaseIndex' in form.problem)
        self.assertEqual(form.form_id, form_id)

        with self.assertRaises(CaseNotFound):
            self.casedb.get_case(case_id)

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

        # create parent case
        submit_case_blocks(
            CaseBlock.deprecated_init(case_id=parent_case_id,
                                      create=True,
                                      case_type='cupboard').as_text(),
            self.domain,
        )

        # re-submit form
        result = submit_form_locally(
            instance=form.get_xml(),
            domain=self.domain,
        )
        duplicate_form = result.xform
        self.assertTrue(duplicate_form.is_duplicate)

        case = self.casedb.get_case(case_id)
        self.assertIsNotNone(case)

        form = self.formdb.get_form(form_id)
        self.assertTrue(form.is_normal)
        self.assertIsNone(getattr(form, 'problem', None))
        self.assertEqual(duplicate_form.orig_id, form.form_id)
示例#13
0
    def test_reprocess_unfinished_submission_case_update(self):
        case_id = uuid.uuid4().hex
        form_ids = []
        form_ids.append(
            submit_case_blocks(
                CaseBlock.deprecated_init(case_id=case_id,
                                          create=True,
                                          case_type='box').as_text(),
                self.domain)[0].form_id)

        with _patch_save_to_raise_error(self):
            submit_case_blocks(
                CaseBlock.deprecated_init(case_id=case_id,
                                          update={
                                              'prop': 'a'
                                          }).as_text(), self.domain)

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

        form_ids.append(stubs[0].xform_id)

        # submit second form with case update
        form_ids.append(
            submit_case_blocks(
                CaseBlock.deprecated_init(case_id=case_id,
                                          update={
                                              'prop': 'b'
                                          }).as_text(),
                self.domain)[0].form_id)

        case = self.casedb.get_case(case_id)
        self.assertEqual(2, len(case.xform_ids))
        self.assertEqual('b', case.get_case_property('prop'))

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

        case = self.casedb.get_case(case_id)
        self.assertEqual('b', case.get_case_property(
            'prop'))  # should be property value from most recent form
        self.assertEqual(3, len(case.xform_ids))
        self.assertEqual(form_ids, case.xform_ids)

        with self.assertRaises(UnfinishedSubmissionStub.DoesNotExist):
            UnfinishedSubmissionStub.objects.get(pk=stubs[0].pk)
示例#14
0
    def test_case_management(self):
        form_id = uuid.uuid4().hex
        case_id = uuid.uuid4().hex
        owner_id = uuid.uuid4().hex
        case_block = CaseBlock.deprecated_init(create=True,
                                               case_id=case_id,
                                               case_type='person',
                                               owner_id=owner_id,
                                               update={
                                                   'property': 'original value'
                                               }).as_text()
        submit_case_blocks(case_block, domain=self.domain, form_id=form_id)

        # validate some assumptions
        case = self.casedb.get_case(case_id)
        self.assertEqual(case.type, 'person')
        self.assertEqual(case.dynamic_case_properties()['property'],
                         'original value')
        self.assertEqual([form_id], case.xform_ids)

        if not getattr(settings, 'TESTS_SHOULD_USE_SQL_BACKEND', False):
            self.assertEqual(2, len(case.actions))
            for a in case.actions:
                self.assertEqual(form_id, a.xform_id)

        # submit a new form with a different case update
        case_block = CaseBlock.deprecated_init(create=True,
                                               case_id=case_id,
                                               case_type='newtype',
                                               owner_id=owner_id,
                                               update={
                                                   'property': 'edited value'
                                               }).as_text()
        xform, _ = submit_case_blocks(case_block,
                                      domain=self.domain,
                                      form_id=form_id)

        case = self.casedb.get_case(case_id)
        self.assertEqual(case.type, 'newtype')
        self.assertEqual(case.dynamic_case_properties()['property'],
                         'edited value')
        self.assertEqual([form_id], case.xform_ids)
        self.assertEqual(case.server_modified_on, xform.edited_on)

        if not getattr(settings, 'TESTS_SHOULD_USE_SQL_BACKEND', False):
            self.assertEqual(2, len(case.actions))
            for a in case.actions:
                self.assertEqual(form_id, a.xform_id)
示例#15
0
    def test_undelete_system_forms(self):
        case_ids = [uuid.uuid4().hex, uuid.uuid4().hex, uuid.uuid4().hex]

        # create 3 cases
        caseblocks = []
        for case_id in case_ids:
            owner_id = self.commcare_user._id

            caseblocks.append(
                CaseBlock.deprecated_init(
                    create=True,
                    case_id=case_id,
                    owner_id=owner_id,
                    user_id=owner_id,
                ).as_text())
        submit_case_blocks(caseblocks, self.domain, user_id=owner_id)[0]

        # submit a system form to update one, and another to update two
        caseblocks = [
            CaseBlock.deprecated_init(
                create=False,
                case_id=case_id,
                user_id=SYSTEM_USER_ID,
                update={
                    'foo': 'bar'
                },
            ).as_text() for case_id in case_ids
        ]
        xform_1 = submit_case_blocks(caseblocks[:1],
                                     self.domain,
                                     user_id=SYSTEM_USER_ID)[0]
        xform_2 = submit_case_blocks(caseblocks[1:],
                                     self.domain,
                                     user_id=SYSTEM_USER_ID)[0]

        # Both forms should be deleted on `retire()`
        self.commcare_user.retire(deleted_by=None)
        form_1 = FormAccessors(self.domain).get_form(xform_1.form_id)
        self.assertTrue(form_1.is_deleted)
        form_2 = FormAccessors(self.domain).get_form(xform_2.form_id)
        self.assertTrue(form_2.is_deleted)

        # Both forms should be undeleted on `unretire()`
        self.commcare_user.unretire(unretired_by=None)
        form_1 = FormAccessors(self.domain).get_form(xform_1.form_id)
        self.assertFalse(form_1.is_deleted)
        form_2 = FormAccessors(self.domain).get_form(xform_2.form_id)
        self.assertFalse(form_2.is_deleted)
示例#16
0
    def test_case_block_index_default_relationship(self):
        """
        CaseBlock index relationship should default to "child"
        """
        case_block = CaseBlock.deprecated_init(
            case_id='123456',
            case_type='newborn',
            date_modified='2015-07-24',
            date_opened='2015-07-24',
            index={
                'parent': ChildIndexAttrs(case_type='mother', case_id='789abc')
            },
        )

        self.assertEqual(
            ElementTree.tostring(case_block.as_xml(),
                                 encoding='utf-8').decode('utf-8'),
            re.sub(
                r'(\n| {2,})', '', """
            <case case_id="123456" date_modified="2015-07-24" xmlns="http://commcarehq.org/case/transaction/v2">
                <update>
                    <case_type>newborn</case_type>
                    <date_opened>2015-07-24</date_opened>
                </update>
                <index>
                    <parent case_type="mother">789abc</parent>
                </index>
            </case>
            """))
示例#17
0
    def test_case_block_index_supports_relationship(self):
        """
        CaseBlock index should allow the relationship to be set
        """
        case_block = CaseBlock.deprecated_init(
            case_id='abcdef',
            case_type='at_risk',
            date_modified='2015-07-24',
            date_opened='2015-07-24',
            index={
                'host':
                IndexAttrs(case_type='newborn',
                           case_id='123456',
                           relationship='extension')
            },
        )

        self.assertEqual(
            ElementTree.tostring(case_block.as_xml(),
                                 encoding='utf-8').decode('utf-8'),
            re.sub(
                r'(\n| {2,})', '', """
            <case case_id="abcdef" date_modified="2015-07-24" xmlns="http://commcarehq.org/case/transaction/v2">
                <update>
                    <case_type>at_risk</case_type>
                    <date_opened>2015-07-24</date_opened>
                </update>
                <index>
                    <host case_type="newborn" relationship="extension">123456</host>
                </index>
            </case>
            """))
示例#18
0
    def test_edit_form_that_removes_ledgers(self):
        from corehq.apps.commtrack.tests.util import get_single_balance_block
        form_id = uuid.uuid4().hex
        submit_case_blocks([
            get_single_balance_block(self.case.case_id, self.product_a._id, 100)],
            DOMAIN,
            form_id=form_id
        )

        self._assert_ledger_state(100)

        transactions = CaseAccessorSQL.get_transactions(self.case.case_id)
        self.assertEqual(2, len(transactions))
        self.assertTrue(transactions[0].is_form_transaction)
        self.assertTrue(transactions[1].is_form_transaction)
        self.assertTrue(transactions[1].is_ledger_transaction)

        submit_case_blocks([
            CaseBlock.deprecated_init(case_id=self.case.case_id).as_text()],
            DOMAIN,
            form_id=form_id
        )

        self._assert_ledger_state(0)

        transactions = CaseAccessorSQL.get_transactions(self.case.case_id)
        self.assertEqual(3, len(transactions))
        self.assertTrue(transactions[0].is_form_transaction)
        # ordering not guaranteed since they have the same date
        self.assertTrue(transactions[1].is_form_transaction)
        self.assertFalse(transactions[1].is_ledger_transaction)  # no longer a ledger transaction
        self.assertTrue(transactions[2].is_case_rebuild)

        self._assert_transactions([])
示例#19
0
def update_supply_point_from_location(supply_point, location):
    domain = supply_point.domain
    assert domain == location.domain

    are_different = (
        supply_point.external_id != location.external_id or
        supply_point.name != location.name or
        supply_point.location_id != location.location_id
    )

    if are_different:
        kwargs = {'external_id': location.external_id} if location.external_id else {}
        caseblock = CaseBlock.deprecated_init(
            case_id=supply_point.case_id,
            create=False,
            case_name=location.name,
            user_id=const.get_commtrack_user_id(location.domain),
            update={
                'location_id': location.location_id,
            },
            **kwargs
        )
        _submit_commtrack_caseblock(domain, caseblock, "update_supply_point_from_location")
        return SupplyInterface(domain).get_supply_point(supply_point.case_id)
    else:
        return supply_point
示例#20
0
    def test_multiple_case_blocks_some_deleted(self, rebuild_case):
        """ Don't rebuild deleted cases """

        case_ids = [uuid.uuid4().hex, uuid.uuid4().hex, uuid.uuid4().hex]

        for i, case_id in enumerate(case_ids):
            if i == 0:
                # only the first case is owned by the user getting retired
                owner_id = self.other_user._id
            else:
                owner_id = self.commcare_user._id

            caseblock = CaseBlock.deprecated_init(
                create=True,
                case_id=case_id,
                owner_id=owner_id,
                user_id=self.commcare_user._id,
            )
            submit_case_blocks(caseblock.as_text(),
                               self.domain,
                               user_id=self.other_user._id)

        self.other_user.retire(deleted_by=None)

        detail = UserArchivedRebuild(user_id=self.other_user.user_id)
        expected_call_args = [
            mock.call(self.domain, case_id, detail) for case_id in case_ids[1:]
        ]

        self.assertEqual(rebuild_case.call_count, len(case_ids) - 1)
        self.assertItemsEqual(rebuild_case.call_args_list, expected_call_args)
示例#21
0
 def case_block(self, case):
     index = case.indices[0]
     return ElementTree.tostring(CaseBlock.deprecated_init(
         create=False,
         case_id=case.case_id,
         index={index.identifier: (index.referenced_type, index.referenced_id, "extension")},
     ).as_xml()).decode('utf-8')
示例#22
0
    def test_fire_signals(self):
        from corehq.apps.receiverwrapper.tests.test_submit_errors import failing_signal_handler
        case_id = uuid.uuid4().hex
        form_id = uuid.uuid4().hex
        with failing_signal_handler('signal death'):
            submit_case_blocks(CaseBlock.deprecated_init(
                case_id=case_id, create=True, case_type='box').as_text(),
                               self.domain,
                               form_id=form_id)

        form = self.formdb.get_form(form_id)

        with catch_signal(
                successful_form_received) as form_handler, catch_signal(
                    case_post_save) as case_handler:
            submit_form_locally(
                instance=form.get_xml(),
                domain=self.domain,
            )

        case = self.casedb.get_case(case_id)

        if should_use_sql_backend(self.domain):
            self.assertEqual(form, form_handler.call_args[1]['xform'])
            self.assertEqual(case, case_handler.call_args[1]['case'])
        else:
            signal_form = form_handler.call_args[1]['xform']
            self.assertEqual(form.form_id, signal_form.form_id)
            self.assertEqual(form.get_rev, signal_form.get_rev)

            signal_case = case_handler.call_args[1]['case']
            self.assertEqual(case.case_id, signal_case.case_id)
            self.assertEqual(case.get_rev, signal_case.get_rev)
示例#23
0
    def test_error_saving(self):
        case_id = uuid.uuid4().hex
        form_id = uuid.uuid4().hex
        with _patch_save_to_raise_error(self):
            submit_case_blocks(CaseBlock.deprecated_init(
                case_id=case_id, create=True, case_type='box').as_text(),
                               self.domain,
                               form_id=form_id)

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

        form = self.formdb.get_form(form_id)
        self.assertTrue(form.is_error)

        with self.assertRaises(CaseNotFound):
            self.casedb.get_case(case_id)

        result = submit_form_locally(
            instance=form.get_xml(),
            domain=self.domain,
        )
        duplicate_form = result.xform
        self.assertTrue(duplicate_form.is_duplicate)

        case = self.casedb.get_case(case_id)
        self.assertIsNotNone(case)

        form = self.formdb.get_form(form_id)
        self.assertTrue(form.is_normal)
        self.assertIsNone(getattr(form, 'problem', None))
        self.assertEqual(duplicate_form.orig_id, form.form_id)
示例#24
0
def case_block(case):
    return ElementTree.tostring(
        CaseBlock.deprecated_init(
            create=False,
            case_id=case['_id'],
            owner_id=case['location_id'],
        ).as_xml())
示例#25
0
    def test_multiple_case_blocks_all_rebuilt(self, rebuild_case):
        """ Rebuild all cases in forms with multiple case blocks """

        case_ids = [uuid.uuid4().hex, uuid.uuid4().hex, uuid.uuid4().hex]

        caseblocks = [
            CaseBlock.deprecated_init(
                create=True,
                case_id=case_id,
                owner_id=self.commcare_user._id,
                user_id=self.commcare_user._id,
            ) for case_id in case_ids
        ]
        casexmls = [
            ElementTree.tostring(caseblock.as_xml()).decode('utf-8')
            for caseblock in caseblocks
        ]
        submit_case_blocks(casexmls, self.domain, user_id=self.other_user._id)

        self.other_user.retire(deleted_by=None)

        detail = UserArchivedRebuild(user_id=self.other_user.user_id)
        expected_call_args = [
            mock.call(self.domain, case_id, detail) for case_id in case_ids
        ]

        self.assertEqual(rebuild_case.call_count, len(case_ids))
        self.assertItemsEqual(rebuild_case.call_args_list, expected_call_args)
示例#26
0
    def test_long_value_validation(self):
        case_id = uuid.uuid4().hex
        case = CaseBlock.deprecated_init(
            create=True,
            case_id=case_id,
            user_id='user1',
            owner_id='user1',
            case_type='demo',
            case_name=
            'this is a very long case name that exceeds the 255 char limit' *
            5)

        xform, cases = post_case_blocks([case.as_xml()], domain=DOMAIN)
        self.assertEqual(0, len(cases))
        self.assertTrue(xform.is_error)
        self.assertIn('CaseValueError', xform.problem)
示例#27
0
    def test_all_case_forms_deleted(self):
        from corehq.apps.callcenter.sync_user_case import sync_usercase
        sync_usercase(self.commcare_user)

        user_case_id = self.commcare_user.get_usercase_id()

        # other user submits form against the case (should get deleted)
        caseblock = CaseBlock.deprecated_init(
            create=False,
            case_id=user_case_id,
        )
        submit_case_blocks(caseblock.as_text(),
                           self.domain,
                           user_id=self.other_user._id)

        case_ids = CaseAccessors(self.domain).get_case_ids_by_owners(
            [self.commcare_user._id])
        self.assertEqual(1, len(case_ids))

        form_ids = FormAccessors(self.domain).get_form_ids_for_user(
            self.commcare_user._id)
        self.assertEqual(0, len(form_ids))

        user_case = self.commcare_user.get_usercase()
        self.assertEqual(2, len(user_case.xform_ids))

        self.commcare_user.retire(deleted_by=None)

        for form_id in user_case.xform_ids:
            self.assertTrue(
                FormAccessors(self.domain).get_form(form_id).is_deleted)

        self.assertTrue(
            CaseAccessors(self.domain).get_case(user_case_id).is_deleted)
示例#28
0
def _submit_case_block(create, case_id, **kwargs):
    domain = kwargs.pop('domain', DOMAIN)
    return post_case_blocks([
        CaseBlock.deprecated_init(create=create, case_id=case_id, **
                                  kwargs).as_xml()
    ],
                            domain=domain)
 def setUp(self):
     self.domain = create_domain(DOMAIN)
     self.user = CommCareUser.create(DOMAIN, USERNAME, PASSWORD, None, None)
     initialize_index_and_mapping(get_es_new(), CASE_SEARCH_INDEX_INFO)
     CaseSearchConfig.objects.get_or_create(pk=DOMAIN, enabled=True)
     delete_all_cases()
     self.case_id = uuid4().hex
     _, [self.case] = post_case_blocks([
         CaseBlock.deprecated_init(
             create=True,
             case_id=self.case_id,
             case_type=CASE_TYPE,
             case_name=CASE_NAME,
             external_id=CASE_NAME,
             user_id=OWNER_ID,
             owner_id=OWNER_ID,
             update={
                 'opened_by': OWNER_ID
             },
         ).as_xml()
     ], {'domain': DOMAIN})
     domains_needing_search_index.clear()
     CaseSearchReindexerFactory(domain=DOMAIN).build().reindex()
     es = get_es_new()
     es.indices.refresh(CASE_SEARCH_INDEX)
示例#30
0
def reassign_household(domain,
                       household_case_id,
                       old_owner_id,
                       new_owner_id,
                       supervisor_id,
                       deprecation_time=None,
                       household_child_case_ids=None):
    from custom.icds.location_reassignment.tasks import process_ucr_changes
    if deprecation_time is None:
        deprecation_time = datetime.utcnow()
    if household_child_case_ids:
        case_ids = household_child_case_ids
    else:
        case_ids = get_household_child_case_ids_by_owner(
            domain, household_case_id, old_owner_id)
    case_ids.append(household_case_id)
    case_blocks = []
    for case_id in case_ids:
        updates = {
            'location_reassignment_last_owner_id': old_owner_id,
            'location_reassignment_datetime': deprecation_time
        }
        if supervisor_id:
            updates['location_reassignment_last_supervisor_id'] = supervisor_id
        case_block = CaseBlock.deprecated_init(case_id,
                                               update=updates,
                                               owner_id=new_owner_id,
                                               user_id=SYSTEM_USER_ID)
        case_block = ElementTree.tostring(case_block.as_xml()).decode('utf-8')
        case_blocks.append(case_block)
    if case_blocks:
        submit_case_blocks(case_blocks, domain, user_id=SYSTEM_USER_ID)
    process_ucr_changes.delay(domain, case_ids)