1 2 3 4 package net.nutch.util; 5 6 import junit.framework.TestCase; 7 8 9 public class TestSuffixStringMatcher extends TestCase { 10 public TestSuffixStringMatcher(String name) { 11 super(name); 12 } 13 14 private final static int NUM_TEST_ROUNDS= 20; 15 private final static int MAX_TEST_SUFFIXES= 100; 16 private final static int MAX_SUFFIX_LEN= 10; 17 private final static int NUM_TEST_INPUTS_PER_ROUND= 100; 18 private final static int MAX_INPUT_LEN= 20; 19 20 private final static char[] alphabet= 21 new char[] { 22 'a', 'b', 'c', 'd', 23 }; 28 29 private String makeRandString(int minLen, int maxLen) { 30 int len= minLen + (int) (Math.random() * (maxLen - minLen)); 31 char[] chars= new char[len]; 32 33 for (int pos= 0; pos < len; pos++) { 34 chars[pos]= alphabet[(int) (Math.random() * alphabet.length)]; 35 } 36 37 return new String (chars); 38 } 39 40 public void testSuffixMatcher() { 41 int numMatches= 0; 42 int numInputsTested= 0; 43 44 for (int round= 0; round < NUM_TEST_ROUNDS; round++) { 45 46 int numSuffixes= (int) (Math.random() * MAX_TEST_SUFFIXES); 48 String [] suffixes= new String [numSuffixes]; 49 for (int i= 0; i < numSuffixes; i++) { 50 suffixes[i]= makeRandString(0, MAX_SUFFIX_LEN); 51 } 52 53 SuffixStringMatcher sufmatcher= new SuffixStringMatcher(suffixes); 54 55 for (int i= 0; i < NUM_TEST_INPUTS_PER_ROUND; i++) { 57 String input= makeRandString(0, MAX_INPUT_LEN); 58 boolean matches= false; 59 int longestMatch= -1; 60 int shortestMatch= -1; 61 62 for (int j= 0; j < suffixes.length; j++) { 63 64 if ((suffixes[j].length() > 0) 65 && input.endsWith(suffixes[j])) { 66 67 matches= true; 68 int matchSize= suffixes[j].length(); 69 70 if (matchSize > longestMatch) 71 longestMatch= matchSize; 72 73 if ( (matchSize < shortestMatch) 74 || (shortestMatch == -1) ) 75 shortestMatch= matchSize; 76 } 77 78 } 79 80 if (matches) 81 numMatches++; 82 83 numInputsTested++; 84 85 assertTrue( "'" + input + "' should " + (matches ? "" : "not ") 86 + "match!", 87 matches == sufmatcher.matches(input) ); 88 if (matches) { 89 assertTrue( shortestMatch 90 == sufmatcher.shortestMatch(input).length()); 91 assertTrue( input.substring(input.length() - shortestMatch).equals( 92 sufmatcher.shortestMatch(input)) ); 93 94 assertTrue( longestMatch 95 == sufmatcher.longestMatch(input).length()); 96 assertTrue( input.substring(input.length() - longestMatch).equals( 97 sufmatcher.longestMatch(input)) ); 98 99 } 100 } 101 } 102 103 System.out.println("got " + numMatches + " matches out of " 104 + numInputsTested + " tests"); 105 } 106 107 } 108 | Popular Tags |