Beispiel #1
0
    def test_to_document(self, include_index, include_source):
        """Test that to_document() creates a dict with the expected keys and values."""
        obj = SimpleModel(id=5,
                          name='test-name',
                          address='123 Fake Street',
                          country='uk')
        doc = SearchSimpleModel.to_document(
            obj,
            include_index=include_index,
            include_source=include_source,
        )
        source = {
            '_document_type': 'simplemodel',
            'id': obj.pk,
            'name': 'test-name',
            'address': '123 Fake Street',
            'country': 'uk',
            'date': None,
        }

        expected_doc = {
            '_id':
            obj.pk,
            **({
                '_index': SearchSimpleModel.get_write_alias()
            } if include_index else {}),
            **({
                '_source': source
            } if include_source else {}),
        }

        assert doc == expected_doc
Beispiel #2
0
    def test_es_document(self, include_index, include_source):
        """Test that es_document() creates a dict with the expected keys and values."""
        obj = SimpleModel(id=5, name='test-name')
        doc = ESSimpleModel.es_document(
            obj,
            include_index=include_index,
            include_source=include_source,
        )
        source = {
            '_document_type': 'simplemodel',
            'id': obj.pk,
            'name': 'test-name',
            'date': None,
        }

        expected_doc = {
            '_id':
            obj.pk,
            '_type':
            DEFAULT_MAPPING_TYPE,
            **({
                '_index': ESSimpleModel.get_write_alias()
            } if include_index else {}),
            **({
                '_source': source
            } if include_source else {}),
        }

        assert doc == expected_doc
Beispiel #3
0
    def test_creates_user_event_log_entries(self, setup_es):
        """Tests that when an export is performed, a user event is recorded."""
        user = create_test_user(permission_codenames=['view_simplemodel'])
        api_client = self.create_api_client(user=user)

        url = reverse('api-v3:search:simplemodel-export')

        simple_obj = SimpleModel(name='test')
        simple_obj.save()
        sync_object_async(ESSimpleModel, SimpleModel, simple_obj.pk)

        setup_es.indices.refresh()

        frozen_time = datetime.datetime(2018, 1, 2, 12, 30, 50, tzinfo=utc)
        with freeze_time(frozen_time):
            response = api_client.post(
                url,
                data={
                    'name': 'test',
                },
            )

        assert response.status_code == status.HTTP_200_OK
        assert UserEvent.objects.count() == 1

        user_event = UserEvent.objects.first()
        assert user_event.adviser == user
        assert user_event.type == USER_EVENT_TYPES.search_export
        assert user_event.timestamp == frozen_time
        assert user_event.api_url_path == '/v3/search/simplemodel/export'
        assert user_event.data == {
            'args': {
                'limit': 100,
                'name': 'test',
                'offset': 0,
                'original_query': '',
                'sortby': None,
            },
            'num_results': 1,
        }
Beispiel #4
0
    def test_signal_receivers_are_not_disabled(self, setup_es, monkeypatch):
        """
        Test that signal receivers are active without the context manager being active.
        """
        callback_mock = Mock()
        monkeypatch.setattr(
            'datahub.search.test.search_support.relatedmodel.signals._dummy_callback',
            callback_mock,
        )

        SimpleModel().save()

        callback_mock.assert_called_once()
Beispiel #5
0
    def test_sorting(self, setup_es):
        """Test to demonstrate how NormalizedKeyword sorts."""
        names = [
            'Alice',
            'Barbara',
            'barbara 2',
            'Álice 2',
            'alice 3',
        ]
        shuffle(names)

        for name in names:
            obj = SimpleModel(name=name)
            obj.save()
            sync_object(SimpleModelSearchApp, obj.pk)

        setup_es.indices.refresh()

        user = create_test_user(permission_codenames=['view_simplemodel'])
        api_client = self.create_api_client(user=user)
        url = reverse('api-v3:search:simplemodel')

        response = api_client.post(
            url,
            data={
                'sortby': 'name',
            },
        )
        response_data = response.json()
        results = response_data['results']

        assert [result['name'] for result in results] == [
            'Alice',
            'Álice 2',
            'alice 3',
            'Barbara',
            'barbara 2',
        ]
Beispiel #6
0
    def test_signal_receivers_disabled_for_model(self, setup_es, monkeypatch):
        """
        Test that signal receivers are disabled for the specified model.

        Note: Model refers to the signal sender, not the search app model. Hence while signal
        receivers are disabled for SimpleModel, it is the relatedmodel app signal receivers that
        are checked.
        """
        callback_mock = Mock()
        monkeypatch.setattr(
            'datahub.search.test.search_support.relatedmodel.signals._dummy_callback',
            callback_mock,
        )

        with disable_search_signal_receivers(SimpleModel):
            SimpleModel().save()

        callback_mock.assert_not_called()
Beispiel #7
0
    def test_pagination(self, es_with_collector, search_support_user):
        """Tests the pagination."""
        total_records = 9
        page_size = 2

        name = 'test record'

        objects = [SimpleModel(name=name) for _ in range(total_records)]

        for obj in objects:
            obj.save()

        # Note: id is a Keyword field, so string sorting must be used
        ids = sorted((obj.id for obj in objects), key=str)

        es_with_collector.flush_and_refresh()

        url = reverse('api-v3:search:basic')
        api_client = self.create_api_client(user=search_support_user)

        for page in range((total_records + page_size - 1) // page_size):
            response = api_client.get(
                url,
                data={
                    'term': name,
                    'entity': 'simplemodel',
                    'offset': page * page_size,
                    'limit': page_size,
                },
            )

            assert response.status_code == status.HTTP_200_OK

            start = page * page_size
            end = start + page_size
            assert ids[start:end] == [
                result['id'] for result in response.data['results']
            ]
Beispiel #8
0
 def _task():
     try:
         SimpleModel().save()
     finally:
         close_old_connections()