def test_author_exists(self):
        author = zeit.content.author.author.Author()
        author.firstname = u'William'
        author.lastname = u'Shakespeare'
        with mock.patch('zeit.find.search.query', lambda **kw: kw):
            with mock.patch('zeit.find.search.search') as search:
                search.return_value = pysolr.Results(None, hits=0)
                self.assertFalse(author.exists)
                search.assert_called_with(
                    dict(fulltext=u'William Shakespeare', types=('author', )))

                search.return_value = pysolr.Results(None, hits=NONZERO)
                self.assertTrue(author.exists)
                search.assert_called_with(
                    dict(fulltext=u'William Shakespeare', types=('author', )))
예제 #2
0
    def _search(self, entity_type, query_string, **extra_kwargs):
        '''
        Query one type of entity. Entities must be queried separately, because
        they each have entity-specific fields in the index, and filtering on
        those specific fields will only return results of the given entity
        type.
        '''
        search_class = self._search_class(entity_type)

        # Don't edit the actual static attribute
        search_kwargs = search_class.search_kwargs.copy()
        search_kwargs.update(extra_kwargs)

        entity_filter = 'id:{}*'.format(entity_type)

        if query_string:
            query_string += ' AND {}'.format(entity_filter)
        else:
            query_string = entity_filter

        results = self.searcher.search(query_string, **search_kwargs)

        if results:
            try:
                self.facets.update({entity_type: results.facets})

            except AttributeError:
                self.facets = {entity_type: results.facets}

        elif results.grouped:
            # This implementation assumes that we're using query grouping in
            # order to retrieve results distinct on the grouped field, e.g.,
            # grouping autosuggestions by slug in order to offer distinct
            # suggestions in the search bar. YMMV!
            grouped_results = []

            for group, group_info in results.grouped.items():
                for members in group_info['groups']:
                    grouped_results += members['doclist']['docs']

            # Mock a Solr response to instantiate a pysolr Results object, per
            # the example here: https://github.com/django-haystack/pysolr/blob/493a9a0f01c80c71836fc5dd4df292599c06b17a/pysolr.py#L251-L285
            result_dict = {
                'response': {
                    'docs': grouped_results,
                    'numFound': len(grouped_results),
                }
            }

            results = pysolr.Results(result_dict)

        # If results contain Employer slugs, replace them with the appropriate
        # Unit and Department objects.
        try:
            results = search_class._format_results(results)
        except AttributeError:
            pass

        return results, results.hits
예제 #3
0
 def search(self, *args, **kw):
     try:
         return super(SolrConnection, self).search(*args, **kw)
     except pysolr.SolrError, e:
         if self.ignore_search_errors:
             log.warn(str(e))
             return pysolr.Results(docs=(), hits=0)
         else:
             raise
예제 #4
0
    def setup_class(self):
        self.manager = GolrLayPersonSearch()

        # Mock the PySolr search function to
        # return our test docs
        input_fh = os.path.join(os.path.dirname(__file__),
                                'resources/solr/layperson-docs.json')
        input_docs = json.load(open(input_fh))
        self.test_results = pysolr.Results(input_docs)
        self.manager.solr.search = MagicMock(return_value=self.test_results)
예제 #5
0
    def setup_class(self):
        self.manager = GolrSearchQuery(taxon_map=False)

        # Mock the PySolr search function to
        # return our test docs
        input_fh = os.path.join(os.path.dirname(__file__),
                                'resources/solr/input/solr-docs.json')
        input_docs = json.load(open(input_fh))
        self.pysolr_results = pysolr.Results(input_docs)
        self.manager.solr.search = MagicMock(return_value=self.pysolr_results)
예제 #6
0
    def setup_class(self):
        self.golr_query = GolrAssociationQuery()

        # Mock the PySolr search function to
        # return our test docs
        input_fh = os.path.join(os.path.dirname(__file__),
                                'resources/solr/mock-solr-evidence.json')
        input_docs = json.load(open(input_fh))
        self.pysolr_results = pysolr.Results(input_docs)
        self.golr_query.solr.search = MagicMock(
            return_value=self.pysolr_results)
예제 #7
0
    def setUp(self):
        self.pysolr_zoo_patcher = mock.patch(
            "proxies.solr.client.pysolr.ZooKeeper"
        )
        self.zoo_mock = self.pysolr_zoo_patcher.start()
        self.zoo_mock.return_value = "zookeeper"
        self.pysolr_solr_patcher = mock.patch(
            "proxies.solr.client.pysolr.SolrCloud"
        )

        self.data = [
            {
                "velocidade": "34",
                "lat": "-11.0000",
                "uuid": f"{uuid.uuid4()}",
                "lon": "-41.0000",
                "placa": "XXX1234",
                "datapassagem": "2020-03-09T14:04:12Z",
                "num_camera": "0000001",
                "faixa": "1",
                "_version_": 1111111111111111111111,
            },
            {
                "velocidade": "35",
                "lat": "-12.0000",
                "uuid": f"{uuid.uuid4()}",
                "lon": "-42.0000",
                "placa": "ZZZ9876",
                "datapassagem": "2020-03-20T19:04:09Z",
                "num_camera": "000002",
                "faixa": "1",
                "_version_": 22222222222222222,
            },
        ]
        self.resp = pysolr.Results(
            {"response": {"docs": self.data, "numFound": 2}}
        )
        self.solr_mock = self.pysolr_solr_patcher.start()

        self.solr_client_mock = mock.Mock(name="cliente")
        self.solr_client_mock.search.return_value = self.resp

        self.solr_mock.return_value = self.solr_client_mock

        self.query = "select * from dual"
        self.start = 1
        self.rows = 10
예제 #8
0
def test_clinical_modifiers():
    """
    Test that clinical modifiers show up in the GolrAssociationQuery.exec() object
    when present in the input solr document
    """
    manager = GolrAssociationQuery()
    manager.solr = pysolr.Solr(url="mock_solr", timeout=10)
    input_fh = os.path.join(os.path.dirname(__file__),
                            'resources/solr/input/clinical-mod-doc.json')
    input_docs = json.load(open(input_fh))
    expected_fh = os.path.join(os.path.dirname(__file__),
                               'resources/solr/expected/clinical-mod.json')
    expected_obj = json.load(open(expected_fh))

    manager.solr.search = MagicMock(return_value=pysolr.Results(input_docs))
    results = manager.exec()
    assert json.dumps(expected_obj, sort_keys=True) == \
           json.dumps(results,
                      default=lambda obj: getattr(obj, '__dict__', str(obj)),
                      sort_keys=True)
예제 #9
0
    def test_autocomplete_no_category(self):
        """
        Test for document without a category
        """
        # Provide a new mock file
        input_fh = os.path.join(os.path.dirname(__file__),
                                'resources/solr/autocomplete-nocat.json')
        input_docs = json.load(open(input_fh))
        self.test_results = pysolr.Results(input_docs)
        self.manager.solr.search = MagicMock(return_value=self.test_results)

        expected_fh = os.path.join(
            os.path.dirname(__file__),
            'resources/solr/autocomplete-nocat-expect.json')
        processed_docs = json.load(open(expected_fh))

        output_docs = self.manager.autocomplete()

        assert json.dumps(processed_docs, sort_keys=True) == \
               json.dumps(output_docs,
                          default=lambda obj: getattr(obj, '__dict__', str(obj)),
                          sort_keys=True)