def test_convert_answers_to_payload_0_0_1_with_key_error(self):
        with self._app.test_request_context():
            user_answer = [create_answer('ABC', '2016-01-01', group_id='group-1', block_id='block-1'),
                           create_answer('DEF', '2016-03-30', group_id='group-1', block_id='block-1'),
                           create_answer('GHI', '2016-05-30', group_id='group-1', block_id='block-1')]

            questionnaire = make_schema('0.0.1', 'section-1', 'group-1', 'block-1', [
                {
                    'id': 'question-1',
                    'answers': [
                        {
                            'id': 'LMN',
                            'type': 'TextField',
                            'q_code': '001'
                        },
                        {
                            'id': 'DEF',
                            'type': 'TextField',
                            'q_code': '002'
                        },
                        {
                            'id': 'JKL',
                            'type': 'TextField',
                            'q_code': '003'
                        }
                    ]
                }
            ])

            routing_path = [Location(group_id='group-1', group_instance=0, block_id='block-1')]
            answer_object = (convert_answers_to_payload_0_0_1(AnswerStore(user_answer), QuestionnaireSchema(questionnaire), routing_path))
            self.assertEqual(answer_object['002'], '2016-03-30')
            self.assertEqual(len(answer_object), 1)
Exemplo n.º 2
0
def convert_answers(metadata, schema, answer_store, routing_path, flushed=False):
    """
    Create the JSON answer format for down stream processing
    :param metadata: metadata for the questionnaire
    :param schema: QuestionnaireSchema class with populated schema json
    :param answer_store: the users answers
    :param routing_path: the path followed by the user when answering the questionnaire
    :param flushed: True when system submits the users answers, False when user submits there own answers
    :return: a JSON object in the following format:
      {
        'tx_id': '0f534ffc-9442-414c-b39f-a756b4adc6cb',
        'type' : 'uk.gov.ons.edc.eq:surveyresponse',
        'version' : '0.0.1',
        'origin' : 'uk.gov.ons.edc.eq',
        'survey_id': '021',
        'flushed': true|false
        'collection':{
          'exercise_sid': 'hfjdskf',
          'instrument_id': 'yui789',
          'period': '2016-02-01'
        },
        'started_at': '2016-03-06T15:28:05Z',
        'submitted_at': '2016-03-07T15:28:05Z',
        'metadata': {
          'user_id': '789473423',
          'ru_ref': '432423423423'
        },
        'data': {}
      }
    """
    survey_id = schema.json['survey_id']
    submitted_at = datetime.now(timezone.utc)
    payload = {
        'tx_id': metadata['tx_id'],
        'type': 'uk.gov.ons.edc.eq:surveyresponse',
        'version': schema.json['data_version'],
        'origin': 'uk.gov.ons.edc.eq',
        'survey_id': survey_id,
        'flushed': flushed,
        'submitted_at': submitted_at.isoformat(),
        'collection': _build_collection(metadata),
        'metadata': _build_metadata(metadata),
    }
    if 'started_at' in metadata and metadata['started_at']:
        payload['started_at'] = metadata['started_at']
    if 'case_id' in metadata and metadata['case_id']:
        payload['case_id'] = metadata['case_id']
    if 'case_ref' in metadata and metadata['case_ref']:
        payload['case_ref'] = metadata['case_ref']

    if schema.json['data_version'] == '0.0.2':
        payload['data'] = convert_answers_to_payload_0_0_2(answer_store, schema, routing_path)
    elif schema.json['data_version'] == '0.0.1':
        payload['data'] = convert_answers_to_payload_0_0_1(answer_store, schema, routing_path)
    else:
        raise DataVersionError(schema.json['data_version'])

    logger.info('converted answer ready for submission')
    return payload
def test_convert_answers_to_payload_0_0_1_with_key_error(
        fake_questionnaire_store):
    fake_questionnaire_store.answer_store = AnswerStore([
        Answer("ABC", "2016-01-01").to_dict(),
        Answer("DEF", "2016-03-30").to_dict(),
        Answer("GHI", "2016-05-30").to_dict(),
    ])

    question = {
        "id":
        "question-1",
        "answers": [
            {
                "id": "LMN",
                "type": "TextField",
                "q_code": "001"
            },
            {
                "id": "DEF",
                "type": "TextField",
                "q_code": "002"
            },
            {
                "id": "JKL",
                "type": "TextField",
                "q_code": "003"
            },
        ],
    }

    questionnaire = make_schema("0.0.1", "section-1", "group-1", "block-1",
                                question)

    full_routing_path = [
        RoutingPath(["block-1"], section_id="section-1", list_item_id=None)
    ]
    answer_object = convert_answers_to_payload_0_0_1(
        fake_questionnaire_store.metadata,
        fake_questionnaire_store.response_metadata,
        fake_questionnaire_store.answer_store,
        fake_questionnaire_store.list_store,
        QuestionnaireSchema(questionnaire),
        full_routing_path,
    )
    assert answer_object["002"] == "2016-03-30"
    assert len(answer_object) == 1
def convert_answers(schema, questionnaire_store, routing_path, flushed=False):
    """
    Create the JSON answer format for down stream processing in the following format:
    ```
      {
        'tx_id': '0f534ffc-9442-414c-b39f-a756b4adc6cb',
        'type' : 'uk.gov.ons.edc.eq:surveyresponse',
        'version' : '0.0.1',
        'origin' : 'uk.gov.ons.edc.eq',
        'survey_id': '021',
        'flushed': true|false
        'collection':{
          'exercise_sid': 'hfjdskf',
          'schema_name': 'yui789',
          'period': '2016-02-01'
        },
        'started_at': '2016-03-06T15:28:05Z',
        'submitted_at': '2016-03-07T15:28:05Z',
        'questionnaire_id': '1234567890000000',
        'launch_language_code': 'en',
        'channel': 'RH',
        'metadata': {
          'user_id': '789473423',
          'ru_ref': '432423423423'
        },
        'data': [
            ...
        ],
      }
    ```

    Args:
        schema: QuestionnaireSchema instance with populated schema json
        questionnaire_store: EncryptedQuestionnaireStorage instance for accessing current questionnaire data
        routing_path: The full routing path followed by the user when answering the questionnaire
        flushed: True when system submits the users answers, False when submitted by user.
    Returns:
        Data payload
    """
    metadata = questionnaire_store.metadata
    response_metadata = questionnaire_store.response_metadata
    answer_store = questionnaire_store.answer_store
    list_store = questionnaire_store.list_store

    survey_id = schema.json["survey_id"]
    submitted_at = datetime.utcnow()

    payload = {
        "tx_id":
        metadata["tx_id"],
        "type":
        "uk.gov.ons.edc.eq:surveyresponse",
        "version":
        schema.json["data_version"],
        "origin":
        "uk.gov.ons.edc.eq",
        "survey_id":
        survey_id,
        "flushed":
        flushed,
        "submitted_at":
        submitted_at.isoformat(),
        "collection":
        _build_collection(metadata),
        "metadata":
        _build_metadata(metadata),
        "questionnaire_id":
        metadata["questionnaire_id"],
        "launch_language_code":
        metadata.get("language_code", DEFAULT_LANGUAGE_CODE),
    }

    if metadata.get("channel"):
        payload["channel"] = metadata["channel"]
    if metadata.get("case_type"):
        payload["case_type"] = metadata["case_type"]
    if metadata.get("form_type"):
        payload["form_type"] = metadata["form_type"]
    if metadata.get("region_code"):
        payload["region_code"] = metadata["region_code"]
    if response_metadata.get("started_at"):
        payload["started_at"] = response_metadata["started_at"]
    if metadata.get("case_id"):
        payload["case_id"] = metadata["case_id"]
    if metadata.get("case_ref"):
        payload["case_ref"] = metadata["case_ref"]

    if schema.json["data_version"] == "0.0.3":
        payload["data"] = {
            "answers":
            convert_answers_to_payload_0_0_3(answer_store, list_store, schema,
                                             routing_path),
            "lists":
            list_store.serialize(),
        }
    elif schema.json["data_version"] == "0.0.1":
        payload["data"] = convert_answers_to_payload_0_0_1(
            metadata, answer_store, list_store, schema, routing_path)
    else:
        raise DataVersionError(schema.json["data_version"])

    logger.info("converted answer ready for submission")
    return payload