1 2 3 4 package net.nutch.searcher; 5 6 import java.io.*; 7 import junit.framework.TestCase; 8 import java.util.Arrays ; 9 import net.nutch.analysis.NutchAnalysis; 10 11 public class TestQuery extends TestCase { 12 public TestQuery(String name) { super(name); } 13 14 public void testRequiredTerm() throws Exception { 15 Query query = new Query(); 16 query.addRequiredTerm("bobo"); 17 testQuery(query, "bobo"); 18 } 19 20 public void testProhibitedTerm() throws Exception { 21 Query query = new Query(); 22 query.addProhibitedTerm("bobo"); 23 testQuery(query, "-bobo"); 24 } 25 26 public void testRequiredPhrase() throws Exception { 27 Query query = new Query(); 28 query.addRequiredPhrase(new String [] {"bobo", "bogo"}); 29 testQuery(query, "\"bobo bogo\""); 30 } 31 32 public void testProhibitedPhrase() throws Exception { 33 Query query = new Query(); 34 query.addProhibitedPhrase(new String [] {"bobo", "bogo"}); 35 testQuery(query, "-\"bobo bogo\""); 36 } 37 38 public void testComplex() throws Exception { 39 Query query = new Query(); 40 query.addRequiredTerm("bobo"); 41 query.addProhibitedTerm("bono"); 42 query.addRequiredPhrase(new String [] {"bobo", "bogo"}); 43 query.addProhibitedPhrase(new String [] {"bogo", "bobo"}); 44 testQuery(query, "bobo -bono \"bobo bogo\" -\"bogo bobo\""); 45 } 46 47 public static void testQuery(Query query, String string) throws Exception { 48 testQueryToString(query, string); 49 testQueryParser(query, string); 50 testQueryIO(query, string); 51 } 52 53 public static void testQueryToString(Query query, String string) { 54 assertEquals(query.toString(), string); 55 } 56 57 public static void testQueryParser(Query query, String string) 58 throws Exception { 59 Query after = NutchAnalysis.parseQuery(string); 60 assertEquals(after, query); 61 assertEquals(after.toString(), string); 62 } 63 64 public static void testQueryIO(Query query, String string) throws Exception { 65 ByteArrayOutputStream oBuf = new ByteArrayOutputStream(); 66 DataOutputStream out = new DataOutputStream(oBuf); 67 query.write(out); 68 69 ByteArrayInputStream iBuf = new ByteArrayInputStream(oBuf.toByteArray()); 70 DataInputStream in = new DataInputStream(iBuf); 71 72 Query after = Query.read(in); 73 74 assertEquals(after, query); 75 } 76 77 public void testQueryTerms() throws Exception { 78 testQueryTerms("foo bar", new String [] {"foo", "bar"}); 79 testQueryTerms("\"foo bar\"", new String [] {"foo", "bar"}); 80 testQueryTerms("\"foo bar\" baz", new String [] {"foo", "bar", "baz"}); 81 } 82 83 public static void testQueryTerms(String query, String [] terms) 84 throws Exception { 85 assertTrue(Arrays.equals(NutchAnalysis.parseQuery(query).getTerms(), 86 terms)); 87 } 88 89 public static void main(String [] args) throws Exception { 90 TestQuery test = new TestQuery("test"); 91 test.testComplex(); 92 } 93 94 } 95 | Popular Tags |