add --shared
[pylucene.git] / lucene-java-3.4.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.IndexWriter;
35 import org.apache.lucene.index.IndexWriterConfig;
36 import org.apache.lucene.queryParser.QueryParser;
37 import org.apache.lucene.search.IndexSearcher;
38 import org.apache.lucene.search.TopDocs;
39 import org.apache.lucene.store.Directory;
40 import org.apache.lucene.util._TestUtil;
41
42 /**
43  * Verifies that Lucene MemoryIndex and RAMDirectory have the same behaviour,
44  * returning the same results for queries on some randomish indexes.
45  */
46 public class MemoryIndexTest extends BaseTokenStreamTestCase {
47   private Set<String> queries = new HashSet<String>();
48   
49   public static final int ITERATIONS = 100 * RANDOM_MULTIPLIER;
50
51   @Override
52   public void setUp() throws Exception {
53     super.setUp();
54     queries.addAll(readQueries("testqueries.txt"));
55     queries.addAll(readQueries("testqueries2.txt"));
56   }
57   
58   /**
59    * read a set of queries from a resource file
60    */
61   private Set<String> readQueries(String resource) throws IOException {
62     Set<String> queries = new HashSet<String>();
63     InputStream stream = getClass().getResourceAsStream(resource);
64     BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
65     String line = null;
66     while ((line = reader.readLine()) != null) {
67       line = line.trim();
68       if (line.length() > 0 && !line.startsWith("#") && !line.startsWith("//")) {
69         queries.add(line);
70       }
71     }
72     return queries;
73   }
74   
75   
76   /**
77    * runs random tests, up to ITERATIONS times.
78    */
79   public void testRandomQueries() throws Exception {
80     for (int i = 0; i < ITERATIONS; i++)
81       assertAgainstRAMDirectory();
82   }
83
84   /**
85    * Build a randomish document for both RAMDirectory and MemoryIndex,
86    * and run all the queries against it.
87    */
88   public void assertAgainstRAMDirectory() throws Exception {
89     StringBuilder fooField = new StringBuilder();
90     StringBuilder termField = new StringBuilder();
91  
92     // add up to 250 terms to field "foo"
93     final int numFooTerms = random.nextInt(250 * RANDOM_MULTIPLIER);
94     for (int i = 0; i < numFooTerms; i++) {
95       fooField.append(" ");
96       fooField.append(randomTerm());
97     }
98
99     // add up to 250 terms to field "term"
100     final int numTermTerms = random.nextInt(250 * RANDOM_MULTIPLIER);
101     for (int i = 0; i < numTermTerms; i++) {
102       termField.append(" ");
103       termField.append(randomTerm());
104     }
105     
106     Directory ramdir = newDirectory();
107     Analyzer analyzer = randomAnalyzer();
108     IndexWriter writer = new IndexWriter(ramdir,
109                                          new IndexWriterConfig(TEST_VERSION_CURRENT, analyzer));
110     Document doc = new Document();
111     Field field1 = newField("foo", fooField.toString(), Field.Store.NO, Field.Index.ANALYZED);
112     Field field2 = newField("term", termField.toString(), Field.Store.NO, Field.Index.ANALYZED);
113     doc.add(field1);
114     doc.add(field2);
115     writer.addDocument(doc);
116     writer.close();
117     
118     MemoryIndex memory = new MemoryIndex();
119     memory.addField("foo", fooField.toString(), analyzer);
120     memory.addField("term", termField.toString(), analyzer);
121     assertAllQueries(memory, ramdir, analyzer);  
122     ramdir.close();
123   }
124   
125   /**
126    * Run all queries against both the RAMDirectory and MemoryIndex, ensuring they are the same.
127    */
128   public void assertAllQueries(MemoryIndex memory, Directory ramdir, Analyzer analyzer) throws Exception {
129     IndexSearcher ram = new IndexSearcher(ramdir);
130     IndexSearcher mem = memory.createSearcher();
131     QueryParser qp = new QueryParser(TEST_VERSION_CURRENT, "foo", analyzer);
132     for (String query : queries) {
133       TopDocs ramDocs = ram.search(qp.parse(query), 1);
134       TopDocs memDocs = mem.search(qp.parse(query), 1);
135       assertEquals(ramDocs.totalHits, memDocs.totalHits);
136     }
137     ram.close();
138     mem.close();
139   }
140   
141   /**
142    * Return a random analyzer (Simple, Stop, Standard) to analyze the terms.
143    */
144   private Analyzer randomAnalyzer() {
145     switch(random.nextInt(3)) {
146       case 0: return new MockAnalyzer(random, MockTokenizer.SIMPLE, true);
147       case 1: return new StopAnalyzer(TEST_VERSION_CURRENT);
148       default: return new MockAnalyzer(random, MockTokenizer.WHITESPACE, false);
149     }
150   }
151   
152   /**
153    * Some terms to be indexed, in addition to random words. 
154    * These terms are commonly used in the queries. 
155    */
156   private static final String[] TEST_TERMS = {"term", "Term", "tErm", "TERM",
157       "telm", "stop", "drop", "roll", "phrase", "a", "c", "bar", "blar",
158       "gack", "weltbank", "worlbank", "hello", "on", "the", "apache", "Apache",
159       "copyright", "Copyright"};
160   
161   
162   /**
163    * half of the time, returns a random term from TEST_TERMS.
164    * the other half of the time, returns a random unicode string.
165    */
166   private String randomTerm() {
167     if (random.nextBoolean()) {
168       // return a random TEST_TERM
169       return TEST_TERMS[random.nextInt(TEST_TERMS.length)];
170     } else {
171       // return a random unicode term
172       return _TestUtil.randomUnicodeString(random);
173     }
174   }
175 }