def test_should_give_error_if_entity_does_not_exist(self):
     self.get_by_short_code_mock.side_effect = DataObjectNotFound(
         'Entity', "Unique Identification Number (ID)", self.entity_id)
     exception = DataObjectNotFound("Entity",
                                    "Unique Identification Number (ID)",
                                    self.entity_id)
     errors = OrderedDict()
     errors['entity_type'] = exception.message
     errors['entity_id'] = exception.message
     self.assertEqual(
         errors, self.validator.validate(self.values, self.fields,
                                         self.dbm))
     self.get_by_short_code_mock.assert_called_once_with(
         self.dbm, self.entity_id, [self.entity_type])
Esempio n. 2
0
    def test_should_create_questionnaire_with_entity_question(self):
        NAME = "eid"
        LABEL = "Entity ID"
        SLUG = "entity_id"
        TYPE = "string"
        post = {"entity_type": "Water Point", "name": "Test Project"}
        dbm = Mock(spec=DatabaseManager)

        patcher = patch("datawinners.project.helper.generate_questionnaire_code")
        mock = patcher.start()
        mock.return_value = '001'

        expected_data_dict = DataDictType(dbm, NAME, SLUG, TYPE, LABEL)
        self.create_ddtype_mock.return_value = expected_data_dict

        with patch("datawinners.project.helper.get_datadict_type_by_slug") as get_datadict_type_by_slug_mock:
            get_datadict_type_by_slug_mock.side_effect = DataObjectNotFound("", "", "")
            form_model = helper.create_questionnaire(post, dbm)

        self.create_ddtype_mock.assert_called_twice_with(dbm=dbm, name=NAME, slug=SLUG,
                                                         primitive_type=TYPE, description=LABEL)
        self.assertEqual(expected_data_dict, form_model.fields[0].ddtype)

        self.assertEqual(1, len(form_model.fields))
        self.assertEqual(True, form_model.fields[0].is_entity_field)
        self.assertEqual(["Water Point"], form_model.entity_type)
        self.assertFalse(form_model.is_active())
        patcher.stop()
Esempio n. 3
0
 def test_should_create_entity_short_codes(self):
     with patch("mangrove.transport.work_flow.get_entity_count_for_type") as current_count:
         with patch("mangrove.transport.work_flow.get_by_short_code_include_voided") as if_short_code_exists:
             current_count.return_value = 1
             if_short_code_exists.side_effect = DataObjectNotFound('entity','short_code','som2')
             code = _generate_short_code(Mock, 'some_type')
             self.assertEquals(code, 'som2')
Esempio n. 4
0
 def test_should_return_error_if_unique_id_does_not_exist(self):
     values = dict(a='text1', b='text2', code1='invalid_id', code2='valid_code')
     dbm = Mock(spec=DatabaseManager)
     with patch('mangrove.form_model.validators.get_by_short_code') as get_by_short_code:
         get_by_short_code.side_effect = [DataObjectNotFound('Entity','short_code','invalid_id'),Mock(spec=Entity)]
         errors = self.validator.validate(values, self.fields, dbm)
         self.assertEquals(1, len(errors))
         self.assertEquals(errors['code1'],u'Entity with short_code = invalid_id not found.')
Esempio n. 5
0
 def setUp(self):
     self.patcher1 = patch("datawinners.project.helper.create_datadict_type")
     self.patcher2 = patch("datawinners.project.helper.get_datadict_type_by_slug")
     self.create_ddtype_mock = self.patcher1.start()
     self.get_datadict_type_by_slug_mock = self.patcher2.start()
     self.create_ddtype_mock.return_value = Mock(spec=DataDictType)
     self.get_datadict_type_by_slug_mock.side_effect = DataObjectNotFound("", "", "")
     self.dbm = Mock(spec=DatabaseManager)
Esempio n. 6
0
def _entity_by_short_code(dbm, short_code, entity_type):
    rows = dbm.view.entity_by_short_code(key=[entity_type, short_code],
                                         include_docs=True)
    if is_empty(rows):
        raise DataObjectNotFound("Entity", "Unique Identification Number (ID)",
                                 short_code)
    doc = EntityDocument.wrap(rows[0]['doc'])
    return Entity.new_from_doc(dbm, doc)
Esempio n. 7
0
def contact_by_short_code(dbm, short_code):
    rows = dbm.view.by_short_codes(key=[['reporter'], short_code],
                                   reduce=False,
                                   include_docs=True)
    if is_empty(rows):
        raise DataObjectNotFound('reporter',
                                 "Unique Identification Number (ID)",
                                 short_code)
    doc = ContactDocument.wrap(rows[0]['doc'])
    return Contact.new_from_doc(dbm, doc)
Esempio n. 8
0
def get_by_short_code(dbm, short_code, entity_type):
    assert is_string(short_code)
    assert is_sequence(entity_type)
    rows = dbm.load_all_rows_in_view("by_short_codes",
                                     key=[entity_type, short_code],
                                     reduce=False)
    if is_empty(rows):
        raise DataObjectNotFound("Entity", "Unique Identification Number (ID)",
                                 short_code)
    doc_id = rows[0].id
    return Entity.get(dbm, doc_id)
 def test_feed_datasender_is_none_when_migrating_survey_response_with_document_for_owner_id_not_found(self):
     survey_response = Mock(spec=SurveyResponse)
     type(survey_response).owner_uid = PropertyMock(return_value='data_sender_uid')
     type(survey_response).values = PropertyMock(return_value={})
     builder = EnrichedSurveyResponseBuilder(self.dbm, survey_response, self.form_model, {})
     with patch("mangrove.feeds.enriched_survey_response.Contact.get") as get_datasender:
         get_datasender.side_effect = DataObjectNotFound(Entity.__name__, 'id', None)
         data_sender = builder._data_sender()
         self.assertIsNone(data_sender['id'])
         self.assertIsNone(data_sender['last_name'])
         self.assertIsNone(data_sender['mobile_number'])
         self.assertIsNone(data_sender['deleted'])
         self.assertIsNone(data_sender['question_code'])
Esempio n. 10
0
def by_short_codes(dbm, short_codes, entity_type, limit=None):
    kwargs = {'include_docs': True, 'reduce': False}
    if limit:
        kwargs['limit'] = limit

    keys = [[entity_type, short_code] for short_code in short_codes]
    kwargs["keys"] = keys

    rows = dbm.view.by_short_codes(**kwargs)
    if is_empty(rows):
        raise DataObjectNotFound(entity_type[0],
                                 "Unique Identification Number (ID)", "")
    docs = [EntityDocument.wrap(row['doc']) for row in rows]
    return [Entity.new_from_doc(dbm, doc) for doc in docs]
Esempio n. 11
0
def get_datadict_type_by_slug(dbm, slug):
    assert isinstance(dbm, DatabaseManager)
    assert is_string(slug)

    rows = dbm.load_all_rows_in_view('by_datadict_type',
                                     key=slug,
                                     include_docs='true')
    if not len(rows):
        raise DataObjectNotFound("DataDictType", "slug", slug)
    assert len(rows) == 1, "More than one item found for slug %s" % (slug, )

    #  include_docs = 'true' returns the doc as a dict, which has to be wrapped into a DataDictDocument, and then into a DataDictType
    _doc = DataDictDocument.wrap(rows[0].doc)
    return DataDictType.new_from_doc(dbm, _doc)
Esempio n. 12
0
    def test_should_fail_submission_if_invalid_short_code(self):
        form_submission = self._valid_form_submission()
        self.form_model_mock.validate_submission.return_value = form_submission

        self.form_submission_entity_module.get_by_short_code.side_effect = DataObjectNotFound(
            "Entity", 'id', 'short_code')

        with self.assertRaises(DataObjectNotFound):
            self.submission_handler.accept(self.submission_request)

        self.submissionLogger.update_submission_log.assert_called_once_with(
            submission_id=self.SUBMISSION_ID,
            status=False,
            errors=u'Entity with id = short_code not found.',
            in_test_mode=False)
    def test_subject_answer_id_as_value_rather_than_name_when_subject_is_not_existing(self):
        survey_response = Mock(spec=SurveyResponse)
        type(survey_response).values = PropertyMock(return_value={'q1': 'cli001'})
        subject_field = UniqueIdField('clinic','name', 'q1', 'Reporting for Subject')
        builder = EnrichedSurveyResponseBuilder(self.dbm, survey_response, self.form_model, {})

        with patch('mangrove.feeds.enriched_survey_response.by_short_code') as by_short_code:
            by_short_code.side_effect = DataObjectNotFound("Entity", "id", "cli001")

            dictionary = builder._create_answer_dictionary(subject_field)

            self.assertEquals({'id': 'cli001', 'name': '', 'deleted': True}, dictionary.get('answer'))
            self.assertEquals('Reporting for Subject', dictionary.get('label'))
            self.assertEquals('unique_id', dictionary.get('type'))
            self.assertEquals('true', dictionary.get('is_entity_question'))
Esempio n. 14
0
    def test_should_not_duplicate_entity_short_codes(self):
        side_effect_values = [Mock(spec=Entity), DataObjectNotFound('entity','short_code','som3')]

        def side_effect(*args):
            result = side_effect_values.pop(0)
            if isinstance(result, Exception):
                raise result
            return result

        with patch("mangrove.transport.work_flow.get_entity_count_for_type") as current_count:
            with patch("mangrove.transport.work_flow.get_by_short_code_include_voided") as if_short_code_exists:
                current_count.return_value = 1
                if_short_code_exists.side_effect = side_effect
                code = _generate_short_code(Mock, 'so m')
                self.assertEquals(code, 'som3')
Esempio n. 15
0
    def test_should_create_location_question_with_implicit_ddtype(self):
        CODE = "lc3"
        LABEL = "what is your location"
        SLUG = "what_is_your_location"
        TYPE = "geocode"
        post = {"title": LABEL, "code": CODE, "type": TYPE, "is_entity_question": False}

        dbm = Mock(spec=DatabaseManager)

        expected_data_dict = DataDictType(dbm, CODE, SLUG, TYPE, LABEL)
        self.create_ddtype_mock.return_value = expected_data_dict

        with patch("datawinners.project.helper.get_datadict_type_by_slug") as get_datadict_type_by_slug_mock:
            get_datadict_type_by_slug_mock.side_effect = DataObjectNotFound("", "", "")
            location_question = helper.create_question(post, dbm)

        self.create_ddtype_mock.assert_called_once_with(dbm=dbm, name=CODE, slug=SLUG,
                                                        primitive_type=TYPE, description=LABEL)
        self.assertEqual(expected_data_dict, location_question.ddtype)
Esempio n. 16
0
    def test_should_create_integer_question_with_implicit_ddtype(self):
        post = {"title": "What is your age", "code": "age", "type": "integer", "choices": [],
                "is_entity_question": False,
                "range_min": 0, "range_max": 100}

        dbm = Mock(spec=DatabaseManager)

        self.create_ddtype_mock.return_value = DataDictType(dbm, "age", "what_is_your_age", "integer",
                                                            "what is your age")

        with patch("datawinners.project.helper.get_datadict_type_by_slug") as get_datadict_type_by_slug_mock:
            get_datadict_type_by_slug_mock.side_effect = DataObjectNotFound("", "", "")
            integer_question = helper.create_question(post, dbm)

        self.create_ddtype_mock.assert_called_once_with(dbm=dbm, name="age", slug="what_is_your_age",
                                                        primitive_type="integer", description="What is your age")
        self.assertEqual('age', integer_question.ddtype.name)
        self.assertEqual("what is your age", integer_question.ddtype.description)
        self.assertEqual("what_is_your_age", integer_question.ddtype.slug)
        self.assertEqual("integer", integer_question.ddtype.primitive_type)
Esempio n. 17
0
    def test_should_create_text_question_with_implicit_ddtype(self):
        post = {"title": "what is your name", "code": "qc1", "description": "desc1", "type": "text",
                "choices": [],
                "is_entity_question": True, "min_length": 1, "max_length": 15}

        dbm = Mock(spec=DatabaseManager)

        self.create_ddtype_mock.return_value = DataDictType(dbm, "qc1", "what_is_your_name", "text",
                                                            "what is your name")

        with patch("datawinners.project.helper.get_datadict_type_by_slug") as get_datadict_type_by_slug_mock:
            get_datadict_type_by_slug_mock.side_effect = DataObjectNotFound("", "", "")
            text_question = helper.create_question(post, dbm)

        self.create_ddtype_mock.assert_called_once_with(dbm=dbm, name="qc1", slug="what_is_your_name",
                                                        primitive_type="text", description="what is your name")
        self.assertEqual('qc1', text_question.ddtype.name)
        self.assertEqual("what is your name", text_question.ddtype.description)
        self.assertEqual("what_is_your_name", text_question.ddtype.slug)
        self.assertEqual("text", text_question.ddtype.primitive_type)
Esempio n. 18
0
    def get(self, id, object_class, get_or_create=False):
        """
        Return the object from the database with the given
        id. object_class must be given so we know how to wrap the data
        retrieved from the database. If get_or_create is True and
        there is no object in the database with this id then the
        object will be created.
        """
        assert issubclass(object_class, DataObject)

        many = self.get_many([id], object_class)
        if get_or_create and len(many) == 0:
            # create one 'cause none exists
            doc = object_class.__document_class__(id=id)
            doc.store(self.database)
            many.append(object_class.new_from_doc(self, doc))

        if not len(many):
            raise DataObjectNotFound(dataobject_name=object_class.__name__,
                                     param="id",
                                     value=id)

        return many[0]
Esempio n. 19
0
def get_group_by_name(dbm, group_name):
    rows = dbm.load_all_rows_in_view('group_by_name', key=lower(group_name))
    if is_empty(rows):
        raise DataObjectNotFound('group', "Group not found")
    doc = GroupDocument.wrap(rows[0]['value'])
    return Group.new_from_doc(dbm, doc)
Esempio n. 20
0
 def test_should_handle_DataObjectNotFoundException(self):
     exception = DataObjectNotFound('test_entity', 'id', '123')
     exception_message_dict = exception_messages[type(exception)]
     expected_message = exception_message_dict.get(SMS) % ('123')
     response = handle(exception, self.request)
     self.assertEqual(expected_message, response)
Esempio n. 21
0
def dummy_get_by_short_code_include_voided(dbm, short_code, entity_type):
    raise DataObjectNotFound("Entity", "Not found", short_code)