Exemplo n.º 1
0
    def test_should_return_all_subjects_matching_given_subject_type_and_database_name_and_query_text(self):
        user = Mock()
        subject_query_builder = Mock()
        subject_query = SubjectQuery()
        response_creator = Mock()
        subject_query.query_builder = subject_query_builder
        subject_query.response_creator = response_creator
        with patch("datawinners.search.entity_search.SubjectQuery.get_headers") as header_fields:
            with patch("datawinners.search.entity_search.Query._getDatabaseName") as get_db_name:
                get_db_name.return_value = "database_name"
                subject_headers = ["field1", "field2"]
                count_of_all_matching_results = 100
                header_fields.return_value = subject_headers
                query_all_results = Mock()
                query = MagicMock()
                subject_query_builder.get_query.return_value = query
                query.count.return_value = count_of_all_matching_results
                query.__getitem__.return_value = query_all_results
                query_with_criteria = Mock()
                subject_query_builder.add_query_criteria.return_value = query_with_criteria
                response_creator.create_response.return_value = "expected subjects"

                actualSubjects = subject_query.query(user, "subject_type", "query_text")

                subject_query_builder.get_query.assert_called_once_with(doc_type='subject_type',
                                                                           database_name='database_name')
                query.__getitem__assert_called_with(slice(None, count_of_all_matching_results, None))
                subject_query_builder.add_query_criteria.assert_called_with(subject_headers, query_all_results,
                                                                            "query_text")
                response_creator.create_response.assert_called_with(subject_headers, query_with_criteria)
                self.assertEquals(actualSubjects, "expected subjects")
Exemplo n.º 2
0
    def test_should_return_subjects_in_a_paginated_fashion_matching_given_subject_type_and_database_name_and_query_text(
            self):
        user = Mock()
        subject_query_builder = Mock()
        query_params = {
            "start_result_number": 2,
            "number_of_results": 10,
            "sort_field": 'last_name',
            "order": "-",
            "search_text": "query_text",
        }
        subject_query = SubjectQuery(query_params)
        response_creator = Mock()

        subject_query.query_builder = subject_query_builder
        subject_query.response_creator = response_creator
        with patch("datawinners.search.entity_search.SubjectQuery.get_headers"
                   ) as header_fields:
            with patch(
                    "datawinners.search.entity_search.Query._getDatabaseName"
            ) as get_db_name:
                get_db_name.return_value = "database_name"
                subject_headers = ["field1", "field2"]
                header_fields.return_value = subject_headers
                paginated_query = Mock()
                expected_total_result_count = 100
                query = MagicMock()
                subject_query_builder.get_query.return_value = query

                paginated_query.count.return_value = expected_total_result_count
                subject_query_builder.create_paginated_query.return_value = paginated_query
                query_with_criteria = Mock()
                expected_filtered_result_count = 50
                query_with_criteria.count.return_value = expected_filtered_result_count
                subject_query_builder.add_query_criteria.return_value = query_with_criteria
                response_creator.create_response.return_value = "expected subjects"

                filtered_count, total_count, actualSubjects = subject_query.paginated_query(
                    user, "subject_type")

                subject_query_builder.create_paginated_query.assert_called_once_with(
                    query, query_params)
                response_creator.create_response.assert_called_with(
                    subject_headers, query_with_criteria)
                subject_query_builder.add_query_criteria.assert_called_with(
                    query_fields=None,
                    query=paginated_query,
                    query_text="query_text",
                    query_params=query_params)
                self.assertEquals(actualSubjects, "expected subjects")
                self.assertEquals(filtered_count,
                                  expected_filtered_result_count)
                self.assertEquals(total_count, expected_total_result_count)
Exemplo n.º 3
0
    def test_should_return_form_id_appended_question_codes(self):
        subject_query = SubjectQuery()
        user = Mock()
        with patch('datawinners.search.entity_search.get_form_model_by_entity_type') as form_model:
            with patch('datawinners.search.entity_search.get_database_manager') as get_database_manager:
                with patch('datawinners.search.entity_search.header_fields') as header_fields:
                    header_fields.return_value = {'code1':'question1','code2':'question2'}
                    get_database_manager.return_value = Mock(spec=DatabaseManager)
                    form_model.return_value = Mock(spec=FormModel, id='form_id')

                    header_dict = subject_query.get_headers(user, 'subject_type')

                    expected = ['form_id_code1','form_id_code2']
                    self.assertEquals(header_dict,expected)
Exemplo n.º 4
0
def all_subjects_ajax(request, subject_type):
    try:
        user = request.user
        search_parameters = {}
        search_text = request.POST.get('sSearch', '').strip()
        search_parameters.update({"search_text": search_text})
        search_parameters.update(
            {"start_result_number": int(request.POST.get('iDisplayStart'))})
        search_parameters.update(
            {"number_of_results": int(request.POST.get('iDisplayLength'))})
        search_parameters.update(
            {"sort_field": _get_order_field(request.POST, user, subject_type)})
        search_parameters.update(
            {"order": "-" if request.POST.get('sSortDir_0') == "desc" else ""})

        query_count, search_count, subjects = SubjectQuery(
            search_parameters).paginated_query(user, subject_type)
        return HttpResponse(jsonpickle.encode(
            {
                'data': subjects,
                'iTotalDisplayRecords': query_count,
                'iDisplayStart': int(request.POST.get('iDisplayStart')),
                "iTotalRecords": search_count,
                'iDisplayLength': int(request.POST.get('iDisplayLength'))
            },
            unpicklable=False),
                            content_type='application/json')

    except Exception as e:
        datawinners_logger.error("All Subjects Ajax failed")
        datawinners_logger.error(request.POST)
        datawinners_logger.exception(e)
        raise
Exemplo n.º 5
0
def _subject_short_codes_to_delete(request, form_model, entity_type):
    if request.POST.get("all_selected") == 'true':
        search_query = request.POST.get('search_query')
        subject_list = SubjectQuery().query(request.user, entity_type,
                                            search_query)
        short_code_index = header_fields(form_model).keys().index("short_code")
        return [s[short_code_index] for s in subject_list]

    return request.POST['all_ids'].split(';')
Exemplo n.º 6
0
def export_subject(request):
    manager = get_database_manager(request.user)
    query_text = request.POST.get('query_text', '')
    subject_type = request.POST.get('subject_type', '').lower()
    subject_list = SubjectQuery().query(request.user, subject_type, query_text)
    form_model = get_form_model_by_entity_type(manager, [subject_type.lower()])

    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="%s.xls"' % (
        subject_type, )
    field_codes = form_model.field_codes()
    labels = get_subject_headers(form_model.form_fields)
    raw_data = [labels]

    for subject in subject_list:
        raw_data.append(subject)

    wb = get_excel_sheet(raw_data, subject_type)
    add_codes_sheet(wb, form_model.form_code, field_codes)
    wb.save(response)
    return response
Exemplo n.º 7
0
def export_subject(request):
    manager = get_database_manager(request.user)
    query_text = request.POST.get('query_text', '')
    subject_type = request.POST.get('subject_type', '').lower()
    subject_list = SubjectQuery().query(request.user, subject_type, query_text)
    form_model = get_form_model_by_entity_type(manager, [subject_type.lower()])

    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="%s.xls"' % (
        subject_type, )
    field_codes = form_model.field_codes()
    field_codes.insert(0, form_model.form_code)
    labels = get_subject_headers(form_model.form_fields)
    raw_data = []
    headers = OrderedDict([(subject_type, labels), ("codes", field_codes)])

    for subject in subject_list:
        raw_data.append(subject)

    return export_to_new_excel(headers, {subject_type: raw_data},
                               subject_type,
                               hide_codes_sheet=True)
Exemplo n.º 8
0
def _get_response(dbm, form_code, user, response_limit):
    """
    :param dbm: database-manager
    :param form_code: questionnaire-code
    :param user: authenticated-usr
    :param response_limit: limit the number of unique-id returned
    :return: tuple of unique-ids and questionnaire details
    unique-ids is a list of dicts where each dict consist of question-name: question-label
    questionnaire details is a dict of question-name:question-label
    """
    try:
        form_model = get_form_model_by_code(dbm, form_code)
        if not form_model.is_entity_registration_form():
            return None, None
    except FormModelDoesNotExistsException:
        return None, None
    header_dict = header_fields(form_model)
    required_field_names = SubjectQuery().get_headers(
        user, form_model.entity_type[0])
    query = _create_elastic_search_query(form_model.entity_type[0], dbm,
                                         response_limit)
    unique_ids = _create_response(required_field_names, query, header_dict)
    return unique_ids, header_dict
Exemplo n.º 9
0
def _get_order_field(post_dict, user, subject_type):
    order_by = int(post_dict.get('iSortCol_0')) - 1
    headers = SubjectQuery().get_headers(user, subject_type)
    return headers[order_by]