Configured build for Ubuntu and added Stempel polish analyzer
[pylucene.git] / samples / LuceneInAction / lia / advsearching / SecurityFilterTest.py
1 # ====================================================================
2 #   Licensed under the Apache License, Version 2.0 (the "License");
3 #   you may not use this file except in compliance with the License.
4 #   You may obtain a copy of the License at
5 #
6 #       http://www.apache.org/licenses/LICENSE-2.0
7 #
8 #   Unless required by applicable law or agreed to in writing, software
9 #   distributed under the License is distributed on an "AS IS" BASIS,
10 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 #   See the License for the specific language governing permissions and
12 #   limitations under the License.
13 # ====================================================================
14
15 from unittest import TestCase
16 from lucene import \
17      WhitespaceAnalyzer, Document, Field, IndexWriter, Term, \
18      QueryWrapperFilter, RAMDirectory, IndexSearcher, TermQuery
19
20
21 class SecurityFilterTest(TestCase):
22
23     def setUp(self):
24
25         self.directory = RAMDirectory()
26         writer = IndexWriter(self.directory, WhitespaceAnalyzer(), True,
27                              IndexWriter.MaxFieldLength.UNLIMITED)
28
29         # Elwood
30         document = Document()
31         document.add(Field("owner", "elwood",
32                            Field.Store.YES, Field.Index.NOT_ANALYZED))
33         document.add(Field("keywords", "elwoods sensitive info",
34                            Field.Store.YES, Field.Index.ANALYZED))
35         writer.addDocument(document)
36
37         # Jake
38         document = Document()
39         document.add(Field("owner", "jake",
40                            Field.Store.YES, Field.Index.NOT_ANALYZED))
41         document.add(Field("keywords", "jakes sensitive info",
42                            Field.Store.YES, Field.Index.ANALYZED))
43         writer.addDocument(document)
44
45         writer.close()
46
47     def testSecurityFilter(self):
48
49         query = TermQuery(Term("keywords", "info"))
50
51         searcher = IndexSearcher(self.directory, True)
52         topDocs = searcher.search(query, 50)
53         self.assertEqual(2, topDocs.totalHits, "Both documents match")
54
55         jakeFilter = QueryWrapperFilter(TermQuery(Term("owner", "jake")))
56
57         scoreDocs = searcher.search(query, jakeFilter, 50).scoreDocs
58         self.assertEqual(1, len(scoreDocs))
59         self.assertEqual("jakes sensitive info",
60                          searcher.doc(scoreDocs[0].doc).get("keywords"),
61                          "elwood is safe")