001: /*
002: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
003: * (license2)
004: * Initial Developer: H2 Group
005: */
006: package org.h2.test.unit;
007:
008: import org.h2.expression.CompareLike;
009: import org.h2.test.TestBase;
010: import org.h2.value.CompareMode;
011:
012: /**
013: * Tests LIKE pattern matching.
014: */
015: public class TestPattern extends TestBase {
016:
017: public void test() throws Exception {
018: CompareMode mode = new CompareMode(null, null, 100);
019: CompareLike comp = new CompareLike(mode, null, null, null,
020: false);
021: test(comp, "B", "%_");
022: test(comp, "A", "A%");
023: test(comp, "A", "A%%");
024: test(comp, "A_A", "%\\_%");
025:
026: for (int i = 0; i < 10000; i++) {
027: String pattern = getRandomPattern();
028: String value = getRandomValue();
029: test(comp, value, pattern);
030: }
031: }
032:
033: void test(CompareLike comp, String value, String pattern)
034: throws Exception {
035: String regexp = initPatternRegexp(pattern, '\\');
036: boolean resultRegexp = value.matches(regexp);
037: boolean result = comp.test(pattern, value, '\\');
038: if (result != resultRegexp) {
039: error("Error: >" + value + "< LIKE >" + pattern
040: + "< result=" + result + " resultReg="
041: + resultRegexp);
042: }
043: }
044:
045: static String getRandomValue() {
046: StringBuffer buff = new StringBuffer();
047: int len = (int) (Math.random() * 10);
048: String s = "AB_%\\";
049: for (int i = 0; i < len; i++) {
050: buff.append(s.charAt((int) (Math.random() * s.length())));
051: }
052: return buff.toString();
053: }
054:
055: static String getRandomPattern() {
056: StringBuffer buff = new StringBuffer();
057: int len = (int) (Math.random() * 4);
058: String s = "A%_\\";
059: for (int i = 0; i < len; i++) {
060: char c = s.charAt((int) (Math.random() * s.length()));
061: if ((c == '_' || c == '%') && Math.random() > 0.5) {
062: buff.append('\\');
063: } else if (c == '\\') {
064: buff.append(c);
065: }
066: buff.append(c);
067: }
068: return buff.toString();
069: }
070:
071: private String initPatternRegexp(String pattern, char escape)
072: throws Exception {
073: int len = pattern.length();
074: StringBuffer buff = new StringBuffer();
075: for (int i = 0; i < len; i++) {
076: char c = pattern.charAt(i);
077: if (escape == c) {
078: if (i >= len) {
079: error("escape can't be last char");
080: }
081: c = pattern.charAt(++i);
082: buff.append('\\');
083: buff.append(c);
084: } else if (c == '%') {
085: buff.append(".*");
086: } else if (c == '_') {
087: buff.append('.');
088: } else if (c == '\\') {
089: buff.append("\\\\");
090: } else {
091: buff.append(c);
092: }
093: // TODO regexp: there are other chars that need escaping
094: }
095: String regexp = buff.toString();
096: // System.out.println("regexp = " + regexp);
097: return regexp;
098: }
099:
100: }
|