pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / memory / src / test / org / apache / lucene / index / memory / MemoryIndexTest.java
1 package org.apache.lucene.index.memory;
2
3 /**
4  * Licensed to the Apache Software Foundation (ASF) under one or more
5  * contributor license agreements.  See the NOTICE file distributed with
6  * this work for additional information regarding copyright ownership.
7  * The ASF licenses this file to You under the Apache License, Version 2.0
8  * (the "License"); you may not use this file except in compliance with
9  * the License.  You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 import java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.InputStreamReader;
24 import java.util.HashSet;
25 import java.util.Set;
26
27 import org.apache.lucene.analysis.Analyzer;
28 import org.apache.lucene.analysis.BaseTokenStreamTestCase;
29 import org.apache.lucene.analysis.MockAnalyzer;
30 import org.apache.lucene.analysis.MockTokenizer;
31 import org.apache.lucene.analysis.StopAnalyzer;
32 import org.apache.lucene.document.Document;
33 import org.apache.lucene.document.Field;
34 import org.apache.lucene.index.IndexReader;
35 import org.apache.lucene.index.IndexWriter;
36 import org.apache.lucene.index.IndexWriterConfig;
37 import org.apache.lucene.queryParser.QueryParser;
38 import org.apache.lucene.search.IndexSearcher;
39 import org.apache.lucene.search.TopDocs;
40 import org.apache.lucene.store.Directory;
41 import org.apache.lucene.util._TestUtil;
42
43 /**
44  * Verifies that Lucene MemoryIndex and RAMDirectory have the same behaviour,
45  * returning the same results for queries on some randomish indexes.
46  */
47 public class MemoryIndexTest extends BaseTokenStreamTestCase {
48   private Set<String> queries = new HashSet<String>();
49   
50   public static final int ITERATIONS = 100 * RANDOM_MULTIPLIER;
51
52   @Override
53   public void setUp() throws Exception {
54     super.setUp();
55     queries.addAll(readQueries("testqueries.txt"));
56     queries.addAll(readQueries("testqueries2.txt"));
57   }
58   
59   /**
60    * read a set of queries from a resource file
61    */
62   private Set<String> readQueries(String resource) throws IOException {
63     Set<String> queries = new HashSet<String>();
64     InputStream stream = getClass().getResourceAsStream(resource);
65     BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
66     String line = null;
67     while ((line = reader.readLine()) != null) {
68       line = line.trim();
69       if (line.length() > 0 && !line.startsWith("#") && !line.startsWith("//")) {
70         queries.add(line);
71       }
72     }
73     return queries;
74   }
75   
76   
77   /**
78    * runs random tests, up to ITERATIONS times.
79    */
80   public void testRandomQueries() throws Exception {
81     for (int i = 0; i < ITERATIONS; i++)
82       assertAgainstRAMDirectory();
83   }
84
85   /**
86    * Build a randomish document for both RAMDirectory and MemoryIndex,
87    * and run all the queries against it.
88    */
89   public void assertAgainstRAMDirectory() throws Exception {
90     StringBuilder fooField = new StringBuilder();
91     StringBuilder termField = new StringBuilder();
92  
93     // add up to 250 terms to field "foo"
94     final int numFooTerms = random.nextInt(250 * RANDOM_MULTIPLIER);
95     for (int i = 0; i < numFooTerms; i++) {
96       fooField.append(" ");
97       fooField.append(randomTerm());
98     }
99
100     // add up to 250 terms to field "term"
101     final int numTermTerms = random.nextInt(250 * RANDOM_MULTIPLIER);
102     for (int i = 0; i < numTermTerms; i++) {
103       termField.append(" ");
104       termField.append(randomTerm());
105     }
106     
107     Directory ramdir = newDirectory();
108     Analyzer analyzer = randomAnalyzer();
109     IndexWriter writer = new IndexWriter(ramdir,
110                                          new IndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
111     Document doc = new Document();
112     Field field1 = newField("foo", fooField.toString(), Field.Store.NO, Field.Index.ANALYZED);
113     Field field2 = newField("term", termField.toString(), Field.Store.NO, Field.Index.ANALYZED);
114     doc.add(field1);
115     doc.add(field2);
116     writer.addDocument(doc);
117     writer.close();
118     
119     MemoryIndex memory = new MemoryIndex();
120     memory.addField("foo", fooField.toString(), analyzer);
121     memory.addField("term", termField.toString(), analyzer);
122     assertAllQueries(memory, ramdir, analyzer);  
123     ramdir.close();
124   }
125   
126   /**
127    * Run all queries against both the RAMDirectory and MemoryIndex, ensuring they are the same.
128    */
129   public void assertAllQueries(MemoryIndex memory, Directory ramdir, Analyzer analyzer) throws Exception {
130     IndexReader reader = IndexReader.open(ramdir);
131     IndexSearcher ram = new IndexSearcher(reader);
132     IndexSearcher mem = memory.createSearcher();
133     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "foo", analyzer);
134     for (String query : queries) {
135       TopDocs ramDocs = ram.search(qp.parse(query), 1);
136       TopDocs memDocs = mem.search(qp.parse(query), 1);
137       assertEquals(ramDocs.totalHits, memDocs.totalHits);
138     }
139     ram.close();
140     reader.close();
141     mem.close();
142   }
143   
144   /**
145    * Return a random analyzer (Simple, Stop, Standard) to analyze the terms.
146    */
147   private Analyzer randomAnalyzer() {
148     switch(random.nextInt(3)) {
149       case 0: return new MockAnalyzer(random, MockTokenizer.SIMPLE, true);
150       case 1: return new StopAnalyzer(TEST_VERSION_CURRENT);
151       default: return new MockAnalyzer(random, MockTokenizer.WHITESPACE, false);
152     }
153   }
154   
155   /**
156    * Some terms to be indexed, in addition to random words. 
157    * These terms are commonly used in the queries. 
158    */
159   private static final String[] TEST_TERMS = {"term", "Term", "tErm", "TERM",
160       "telm", "stop", "drop", "roll", "phrase", "a", "c", "bar", "blar",
161       "gack", "weltbank", "worlbank", "hello", "on", "the", "apache", "Apache",
162       "copyright", "Copyright"};
163   
164   
165   /**
166    * half of the time, returns a random term from TEST_TERMS.
167    * the other half of the time, returns a random unicode string.
168    */
169   private String randomTerm() {
170     if (random.nextBoolean()) {
171       // return a random TEST_TERM
172       return TEST_TERMS[random.nextInt(TEST_TERMS.length)];
173     } else {
174       // return a random unicode term
175       return _TestUtil.randomUnicodeString(random);
176     }
177   }
178 }