提交 d44bff9d authored 作者: Thomas Mueller's avatar Thomas Mueller

--no commit message

--no commit message
上级 3da434bd
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.util.BitSet;
import java.util.Random;
import org.h2.test.TestBase;
import org.h2.util.BitField;
/**
* @author Thomas
*/
public class TestBitField extends TestBase {
public void test() throws Exception {
testRandom();
testGetSet();
}
void testRandom() throws Exception {
BitField bits = new BitField();
BitSet set = new BitSet();
int max = 300;
int count = 100000;
Random random = new Random(1);
for(int i=0; i<count; i++) {
int idx = random.nextInt(max);
if(random.nextBoolean()) {
if(random.nextBoolean()) {
bits.set(idx);
set.set(idx);
} else {
bits.clear(idx);
set.clear(idx);
}
} else {
check(bits.get(idx), set.get(idx));
check(bits.nextClearBit(idx), set.nextClearBit(idx));
check(bits.nextSetBit(idx), set.nextSetBit(idx));
}
}
}
void testGetSet() throws Exception {
BitField bits = new BitField();
for(int i=0; i<10000; i++) {
bits.set(i);
if(!bits.get(i)) {
throw new Exception("not set: "+i);
}
if(bits.get(i+1)) {
throw new Exception("set: "+i);
}
}
for(int i=0; i<10000; i++) {
if(!bits.get(i)) {
throw new Exception("not set: "+i);
}
}
for(int i=0; i<1000; i++) {
int k = bits.nextClearBit(0);
if(k != 10000) {
throw new Exception("" + k);
}
}
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Random;
import org.h2.test.TestBase;
public class TestCache extends TestBase {
public void test() throws Exception {
deleteDb("cache");
Connection conn = getConnection("cache");
Statement stat = conn.createStatement();
stat.execute("SET CACHE_SIZE 1024");
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
stat.execute("CREATE TABLE MAIN(ID INT PRIMARY KEY, NAME VARCHAR)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
PreparedStatement prep2 = conn.prepareStatement("INSERT INTO MAIN VALUES(?, ?)");
int max = 10000;
for(int i=0; i<max; i++) {
prep.setInt(1, i);
prep.setString(2, "Hello " + i);
prep.execute();
prep2.setInt(1, i);
prep2.setString(2, "World " + i);
prep2.execute();
}
conn.close();
System.out.println("------------------- read ");
conn = getConnection("cache");
stat = conn.createStatement();
stat.execute("SET CACHE_SIZE 1024");
Random random = new Random(1);
for(int i=0; i<100; i++) {
stat.executeQuery("SELECT * FROM MAIN WHERE ID BETWEEN 40 AND 50");
stat.executeQuery("SELECT * FROM MAIN WHERE ID = " + random.nextInt(max));
if((i%10) == 0) {
stat.executeQuery("SELECT * FROM TEST");
}
}
conn.close();
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.util.Random;
import org.h2.test.TestBase;
import org.h2.tools.CompressTool;
public class TestCompress extends TestBase {
public void test() throws Exception {
if(config.big) {
for(int i=0; i<100; i++) {
test(i);
}
for(int i=100; i<10000; i += (i+i+1)) {
test(i);
}
} else {
test(0);
test(1);
test(7);
test(50);
test(200);
}
}
void test(int len) throws Exception {
for(int pattern = 0; pattern < 3; pattern++) {
byte[] buff = new byte[len];
switch(pattern) {
case 0:
// leave empty
break;
case 1: {
for(int x=0; x<len; x++) {
buff[x] = (byte)(x & 10);
}
break;
}
case 2: {
Random r = new Random(len);
r.nextBytes(buff);
break;
}
}
String[] algorithm= new String[]{
"LZF", "Deflate", "No"
};
CompressTool utils = CompressTool.getInstance();
for(int i=0; i<algorithm.length; i++) {
byte[] out = utils.compress(buff, algorithm[i]);
byte[] test = utils.expand(out);
check(test.length, buff.length);
check(buff, test);
}
}
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.sql.SQLException;
import org.h2.store.DataHandler;
import org.h2.store.DataPage;
import org.h2.store.FileStore;
import org.h2.test.TestBase;
import org.h2.value.Value;
import org.h2.value.ValueDouble;
import org.h2.value.ValueFloat;
import org.h2.value.ValueInt;
import org.h2.value.ValueNull;
import org.h2.value.ValueString;
/**
* @author Thomas
*/
public class TestDataPage extends TestBase implements DataHandler {
boolean text;
public void test() throws Exception {
testAll();
text = true;
testAll();
}
private void testAll() throws Exception {
DataPage page = DataPage.create(this, 128);
char[] data = new char[0x10000];
for(int i=0; i<data.length; i++) {
data[i] = (char)i;
}
String s = new String(data);
page.writeString(s);
int len = page.length();
check(page.getStringLen(s), len);
page.reset();
check(s, page.readString());
page.reset();
page.writeString("H\u1111!");
page.writeString("John\tBrack's \"how are you\" M\u1111ller");
page.writeValue(ValueInt.get(10));
page.writeValue(ValueString.get("test"));
page.writeValue(ValueFloat.get(-2.25f));
page.writeValue(ValueDouble.get(10.40));
page.writeValue(ValueNull.INSTANCE);
trace(new String(page.getBytes()));
page.reset();
trace(page.readString());
trace(page.readString());
trace(page.readValue().getInt());
trace(page.readValue().getString());
trace(""+page.readValue().getFloat());
trace(""+page.readValue().getDouble());
trace(page.readValue().toString());
page.reset();
page.writeInt(0);
page.writeInt(Integer.MAX_VALUE);
page.writeInt(Integer.MIN_VALUE);
page.writeInt(1);
page.writeInt(-1);
page.writeInt(1234567890);
page.writeInt(54321);
trace(new String(page.getBytes()));
page.reset();
trace(page.readInt());
trace(page.readInt());
trace(page.readInt());
trace(page.readInt());
trace(page.readInt());
trace(page.readInt());
trace(page.readInt());
page = null;
}
public boolean getTextStorage() {
return text;
}
public String getDatabasePath() {
return null;
}
public FileStore openFile(String name, boolean mustExist) throws SQLException {
return null;
}
public int getChecksum(byte[] data, int start, int end) {
return end-start;
}
public void checkPowerOff() throws SQLException {
}
public void checkWritingAllowed() throws SQLException {
}
public void freeUpDiskSpace() throws SQLException {
}
public void handleInvalidChecksum() throws SQLException {
throw new SQLException();
}
public int compareTypeSave(Value a, Value b) throws SQLException {
throw new SQLException();
}
public int getMaxLengthInplaceLob() {
throw new Error();
}
public int allocateObjectId(boolean b, boolean c) {
throw new Error();
}
public String createTempFile() throws SQLException {
throw new SQLException();
}
public String getLobCompressionAlgorithm(int type) {
throw new Error();
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.h2.api.DatabaseEventListener;
import org.h2.test.TestBase;
public class TestExit extends TestBase implements DatabaseEventListener {
public void test() throws Exception {
if(config.codeCoverage) {
return;
}
String classPath = "bin"+File.pathSeparator+".";
deleteDb("exit");
String[] procDef;
procDef = new String[]{
"java", "-cp", classPath,
getClass().getName(),
"" + OPEN_WITH_CLOSE_ON_EXIT
};
Process proc = Runtime.getRuntime().exec(procDef);
while (true) {
int ch = proc.getErrorStream().read();
if (ch < 0) {
break;
}
System.out.print((char) ch);
}
while (true) {
int ch = proc.getInputStream().read();
if (ch < 0) {
break;
}
System.out.print((char) ch);
}
proc.waitFor();
if(!getClosedFile().exists()) {
error("didnt close database");
}
procDef = new String[]{
"java", "-cp", classPath,
getClass().getName(),
"" + OPEN_WITHOUT_CLOSE_ON_EXIT
};
proc = Runtime.getRuntime().exec(procDef);
proc.waitFor();
if(getClosedFile().exists()) {
error("closed database");
}
}
static final int OPEN_WITH_CLOSE_ON_EXIT = 1, OPEN_WITHOUT_CLOSE_ON_EXIT = 2;
public static Connection conn;
public static void main(String[] args) throws Exception {
if(args.length==0) {
System.exit(1);
}
int action = Integer.parseInt(args[0]);
TestExit app = new TestExit();
app.execute(action);
}
void execute(int action) throws Exception {
Class.forName("org.h2.Driver");
String url = "";
switch(action) {
case OPEN_WITH_CLOSE_ON_EXIT:
url = "jdbc:h2:exit;database_event_listener='" + getClass().getName() + "';db_close_on_exit=true";
break;
case OPEN_WITHOUT_CLOSE_ON_EXIT:
url = "jdbc:h2:exit;database_event_listener='" + getClass().getName() + "';db_close_on_exit=false";
break;
}
conn = open(url);
Connection conn2 = open(url);
conn2.close();
}
private static Connection open(String url) throws Exception {
getClosedFile().delete();
return DriverManager.getConnection(url, "sa", "");
}
public void diskSpaceIsLow(long stillAvailable) throws SQLException {
}
public void exceptionThrown(SQLException e) {
}
public void closingDatabase() {
try {
getClosedFile().createNewFile();
} catch(IOException e) {
e.printStackTrace();
}
}
private static File getClosedFile() {
return new File(BASE_DIR + "/closed.txt");
}
public void setProgress(int state, String name, int x, int max) {
}
public void init(String url) {
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.io.File;
import org.h2.message.TraceSystem;
import org.h2.store.FileLock;
import org.h2.test.TestBase;
import org.h2.util.FileUtils;
/**
* @author Thomas
*/
public class TestFileLock extends TestBase implements Runnable {
int wait;
static final int KILL = 10;
static final String FILE = BASE_DIR + "/test.lock";
private boolean allowSockets;
private static volatile int locks;
private static volatile boolean stop;
public TestFileLock() {}
public void test() throws Exception {
new File(FILE).delete();
int threadCount = getSize(3, 5);
wait = getSize(20, 200);
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++) {
threads[i] = new Thread(new TestFileLock(this, false));
threads[i].start();
Thread.sleep(wait + (int) (Math.random() * wait));
}
trace("wait");
Thread.sleep(100);
stop = true;
trace("STOP file");
for (int i = 0; i < threadCount; i++) {
threads[i].join();
}
check(locks, 0);
FileUtils.delete(FILE);
stop = false;
for (int i = 0; i < threadCount; i++) {
threads[i] = new Thread(new TestFileLock(this, true));
threads[i].start();
Thread.sleep(wait + (int) (Math.random() * wait));
}
trace("wait");
Thread.sleep(100);
stop = true;
trace("STOP sockets");
for (int i = 0; i < threadCount; i++) {
threads[i].join();
}
check(locks, 0);
}
TestBase base;
TestFileLock(TestBase base, boolean allowSockets) {
this.base = base;
this.allowSockets = allowSockets;
}
public void run() {
while (!stop) {
FileLock lock = new FileLock(new TraceSystem(null), 100);
try {
lock.lock(FILE, allowSockets);
base.trace(lock + " locked");
locks++;
if (locks > 1) {
System.err.println("ERROR! LOCKS=" + locks);
stop = true;
}
Thread.sleep(wait + (int) (Math.random() * wait));
locks--;
if ((Math.random() * 50) < KILL) {
base.trace(lock + " kill");
lock = null;
System.gc();
} else {
base.trace(lock + " unlock");
lock.unlock();
}
if (locks < 0) {
System.err.println("ERROR! LOCKS=" + locks);
stop = true;
}
} catch (Exception e) {
// log(id+" cannot lock: " + e);
// e.printStackTrace();
}
try {
Thread.sleep(wait + (int) (Math.random() * wait));
} catch (InterruptedException e1) {
// ignore
}
}
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.util.Arrays;
import java.util.Random;
import org.h2.test.TestBase;
import org.h2.util.IntArray;
public class TestIntArray extends TestBase {
public void test() throws Exception {
IntArray array = new IntArray();
int[] test = new int[0];
Random random = new Random(1);
for(int i=0; i<10000; i++) {
int idx = test.length == 0 ? 0 : random.nextInt(test.length);
int v = random.nextInt(100);
int op = random.nextInt(9);
switch(op) {
case 0:
array.add(idx, v);
test = add(test, idx, v);
break;
case 1:
array.add(v);
test = add(test, v);
break;
case 2:
array.sort();
test = sort(test);
array.addValueSorted(v);
test = addValueSorted(test, v);
break;
case 3:
array.sort();
test = sort(test);
int a = array.findNextValueIndex(v);
int b = findNextValueIndex(test, v);
check(a, b);
break;
case 4:
if(test.length > idx) {
check(array.get(idx), get(test, idx));
}
break;
case 5:
array.remove(idx);
test = remove(test, idx);
break;
case 6:
if(test.length > idx) {
v = test[idx];
array.removeValue(v);
test = removeValue(test, v);
}
break;
case 7:
array.set(idx, v);
test = set(test, idx, v);
break;
case 8:
check(array.size(), test.length);
break;
}
check(array.size(), test.length);
for(int j=0; j<test.length; j++) {
check(test[j], array.get(j));
}
}
}
int[] add(int[] array, int i, int value) {
int[] a2 = new int[array.length+1];
System.arraycopy(array, 0, a2, 0, array.length);
if(i < array.length) {
System.arraycopy(a2, i, a2, i+1, a2.length - i - 1);
}
array = a2;
array[i] = value;
return array;
}
int[] add(int[] array, int value) {
return add(array, array.length, value);
}
int[] addValueSorted(int[] array, int value) {
for(int i=0; i<array.length; i++) {
if(array[i] < value) {
continue;
}
if(array[i] == value) {
return array;
} else {
return add(array, i, value);
}
}
return add(array, value);
}
int findNextValueIndex(int[] array, int value) {
for(int i=0; i<array.length; i++) {
if(array[i] >= value) {
return i;
}
}
return array.length;
}
int get(int[] array, int i) {
return array[i];
}
int[] remove(int[] array, int i) {
int[] a2 = new int[array.length-1];
System.arraycopy(array, 0, a2, 0, i);
if(i < a2.length) {
System.arraycopy(array, i+1, a2, i, array.length - i - 1);
}
return a2;
}
int[] removeValue(int[] array, int value) {
for(int i=0; i<array.length; i++) {
if(array[i] == value) {
return remove(array, i);
}
}
return array;
}
int[] set(int[] array, int i, int value) {
array[i] = value;
return array;
}
int size(int[] array) {
return array.length;
}
int[] sort(int[] array) {
Arrays.sort(array);
return array;
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.util.Random;
import org.h2.test.TestBase;
import org.h2.util.IntIntHashMap;
public class TestIntIntHashMap extends TestBase {
Random rand = new Random();
public void test() throws Exception {
rand.setSeed(10);
test(true);
test(false);
}
public void test(boolean random) throws Exception {
int len = 2000;
int[] x = new int[len];
for (int i = 0; i < len; i++) {
int key = random ? rand.nextInt() : i;
x[i] = key;
}
IntIntHashMap map = new IntIntHashMap();
for (int i = 0; i < len; i++) {
map.put(x[i], i);
}
for (int i = 0; i < len; i ++) {
if (map.get(x[i]) != i) {
throw new Error("get " + x[i] + " = " + map.get(i) + " should be " + i);
}
}
for (int i = 1; i < len; i += 2) {
map.remove(x[i]);
}
for (int i = 1; i < len; i += 2) {
if (map.get(x[i]) != -1) {
throw new Error("get " + x[i] + " = " + map.get(i) + " should be <=0");
}
}
for (int i = 1; i < len; i += 2) {
map.put(x[i], i);
}
for (int i = 0; i < len; i ++) {
if (map.get(x[i]) != i) {
throw new Error("get " + x[i] + " = " + map.get(i) + " should be " + i);
}
}
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Random;
import org.h2.engine.Constants;
import org.h2.test.TestBase;
import org.h2.value.Value;
import org.h2.value.ValueString;
public class TestOverflow extends TestBase {
public void test() throws Exception {
test(Value.BYTE, Byte.MIN_VALUE, Byte.MAX_VALUE);
test(Value.INT, Integer.MIN_VALUE, Integer.MAX_VALUE);
test(Value.LONG, Long.MIN_VALUE, Long.MAX_VALUE);
test(Value.SHORT, Short.MIN_VALUE, Short.MAX_VALUE);
}
private ArrayList values;
private int type;
private BigInteger min, max;
private boolean successExpected;
private void test(int type, long min, long max) throws Exception {
values = new ArrayList();
this.type = type;
this.min = new BigInteger(""+min);
this.max = new BigInteger(""+max);
add(0);
add(min);
add(max);
add(max-1);
add(min+1);
add(1);
add(-1);
Random random = new Random(1);
for(int i=0; i<40; i++) {
if(max > Integer.MAX_VALUE) {
add(random.nextLong());
} else {
add((random.nextBoolean() ? 1 : -1) * random.nextInt((int)max));
}
}
for(int a=0; a<values.size(); a++) {
for(int b=0; b<values.size(); b++) {
Value va = (Value) values.get(a);
Value vb = (Value) values.get(b);
testValues(va, vb);
}
}
}
void checkIfExpected(String a, String b) throws Exception {
if(successExpected) {
check(a, b);
}
}
void onSuccess() throws Exception {
if(!successExpected && Constants.OVERFLOW_EXCEPTIONS) {
error("unexpected success");
}
}
void onError() throws Exception {
if(successExpected) {
error("unexpected error");
}
}
private void testValues(Value va, Value vb) throws Exception {
BigInteger a = new BigInteger(va.getString());
BigInteger b = new BigInteger(vb.getString());
successExpected = inRange(a.negate());
try {
checkIfExpected(va.negate().getString(), a.negate().toString());
onSuccess();
} catch(SQLException e) {
onError();
}
successExpected = inRange(a.add(b));
try {
checkIfExpected(va.add(vb).getString(), a.add(b).toString());
onSuccess();
} catch(SQLException e) {
onError();
}
successExpected = inRange(a.subtract(b));
try {
checkIfExpected(va.subtract(vb).getString(), a.subtract(b).toString());
onSuccess();
} catch(SQLException e) {
onError();
}
successExpected = inRange(a.multiply(b));
try {
checkIfExpected(va.multiply(vb).getString(), a.multiply(b).toString());
onSuccess();
} catch(SQLException e) {
onError();
}
}
private boolean inRange(BigInteger v) {
return v.compareTo(min) >= 0 && v.compareTo(max) <= 0;
}
private void add(long l) throws SQLException {
values.add(ValueString.get("" + l).convertTo(type));
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import org.h2.expression.CompareLike;
import org.h2.test.TestBase;
import org.h2.value.CompareMode;
/**
* @author Thomas
*/
public class TestPattern extends TestBase {
public void test() throws Exception {
CompareMode mode = new CompareMode(null, null);
CompareLike comp = new CompareLike(mode, null, null, null);
test(comp, "B", "%_");
test(comp, "A", "A%");
test(comp, "A", "A%%");
for(int i=0; i<10; i++) {
String pattern=getRandomPattern();
String value=getRandomValue();
test(comp, value, pattern);
}
}
void test(CompareLike comp, String value, String pattern) throws Exception {
// TODO test: need another regexp implementation (this one doesn't work for gcj)
// String regexp = initPatternRegexp(pattern);
// boolean resultRegexp = value.matches(regexp);
// boolean result =
comp.test(pattern, value, 'X');
// if(result != resultRegexp) {
// throw new Exception("Error: >"+value+"< LIKE >"+pattern+"< result="+result+" resultReg="+resultRegexp);
// }
}
static String getRandomValue() {
StringBuffer buff = new StringBuffer();
int len = (int)(Math.random() * 10);
String s = "ABCDEFGHIJKLMNOP";
for(int i=0; i<len; i++) {
buff.append(s.charAt((int)(Math.random()*s.length())));
}
return buff.toString();
}
static String getRandomPattern() {
StringBuffer buff = new StringBuffer();
int len = (int)(Math.random() * 4);
//String s = "ABC%_\\";
String s = "AB_";
for(int i=0; i<len; i++) {
buff.append(s.charAt((int)(Math.random()*s.length())));
}
return buff.toString();
}
// private String initPatternRegexp(String pattern) {
// int len = pattern.length();
// StringBuffer buff = new StringBuffer();
// for (int i = 0; i < len; i++) {
// char c = pattern.charAt(i);
// if (escape != null && escape.charValue() == c) {
// if (i >= len) {
// throw Message.internal("escape can't be last char");
// }
// c = pattern.charAt(++i);
// buff.append('\\');
// buff.append(c);
// } else if (c == '%') {
// buff.append(".*");
// } else if (c == '_') {
// buff.append('.');
// } else if(c=='\\'){
// buff.append("\\\\");
// } else {
// buff.append(c);
// }
// // TODO regexp: there are other chars that need escaping
// }
// String regexp = buff.toString();
//// System.out.println("regexp = " + regexp);
// return regexp;
// }
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import org.h2.test.TestBase;
import org.h2.util.IOUtils;
import org.h2.util.TypeConverter;
public class TestReader extends TestBase {
public void test() throws Exception {
String s = "\u00ef\u00f6\u00fc";
StringReader r = new StringReader(s);
InputStream in = TypeConverter.getInputStream(r);
byte[] buff = IOUtils.readBytesAndClose(in, 0);
InputStream in2 = new ByteArrayInputStream(buff);
Reader r2 = TypeConverter.getReader(in2);
String s2 = IOUtils.readStringAndClose(r2, Integer.MAX_VALUE);
check(s2, "\u00ef\u00f6\u00fc");
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Method;
import org.h2.test.TestBase;
import org.h2.util.StringUtils;
public class TestSampleApps extends TestBase {
public void test() throws Exception {
testApp(org.h2.samples.Compact.class, null, "Compacting...\nDone.");
testApp(org.h2.samples.CsvSample.class, null,
"NAME: Bob Meier\n"
+ "EMAIL: bob.meier@abcde.fgh\n"
+"PHONE: +41123456789\n\n"
+"NAME: John Jones\n"
+"EMAIL: johnjones@abcde.fgh\n"
+"PHONE: +41976543210\n");
testApp(org.h2.samples.Function.class, null,
"2 is prime\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime");
testApp(org.h2.samples.SecurePassword.class, null, "Hello");
// TODO test ShowProgress (percent numbers are hardware specific)
// TODO test ShutdownServer (server needs to be started in a separater process)
testApp(org.h2.samples.TriggerSample.class, null, "The sum is 20.00");
// tools
testApp(org.h2.tools.ChangePassword.class, new String[]{"-?"}, "java org.h2.tools.ChangePassword [-dir <dir>] "
+ "[-db <database>] [-cipher <cipher>] [-decrypt <pwd>] [-encrypt <pwd>] [-quiet]");
testApp(org.h2.tools.ChangePassword.class, null, "java org.h2.tools.ChangePassword [-dir <dir>] "
+ "[-db <database>] [-cipher <cipher>] [-decrypt <pwd>] [-encrypt <pwd>] [-quiet]");
testApp(org.h2.tools.DeleteDbFiles.class, new String[]{"-?"}, "java org.h2.tools.DeleteDbFiles [-dir <dir>] [-db <database>] [-quiet]");
}
private void testApp(Class clazz, String[] args, String expected) throws Exception {
Method m = clazz.getMethod("main", new Class[]{String[].class});
PrintStream oldOut = System.out, oldErr = System.err;
ByteArrayOutputStream buff = new ByteArrayOutputStream();
PrintStream out = new PrintStream(buff, false, "UTF-8");
System.setOut(out);
System.setErr(out);
try {
m.invoke(null, new Object[]{args});
} catch(Throwable e) {
System.out.print("EXCEPTION");
e.printStackTrace();
}
out.flush();
System.setOut(oldOut);
System.setErr(oldErr);
String s = new String(buff.toByteArray(), "UTF-8");
s = StringUtils.replaceAll(s, "\r\n", "\n");
check(s.trim(), expected.trim());
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.io.StringReader;
import java.util.Random;
import org.h2.test.TestBase;
import org.h2.util.ScriptReader;
public class TestScriptReader extends TestBase {
public void test() throws Exception {
testCommon();
testRandom();
}
private void testRandom() throws Exception {
int len = getSize(1000, 10000);
Random random = new Random(10);
for(int i=0; i<len; i++) {
int l = random.nextInt(10);
String[] sql = new String[l];
StringBuffer buff = new StringBuffer();
for(int j=0; j<l; j++) {
sql[j] = randomStatement(random);
buff.append(sql[j]);
if(j<l - 1) {
buff.append(";");
}
}
String s = buff.toString();
StringReader reader = new StringReader(s);
ScriptReader source = new ScriptReader(reader);
for(int j=0; j<l; j++) {
String e = source.readStatement();
String c = sql[j];
if(c.length() == 0 && j == l-1) {
c = null;
}
check(e, c);
}
check(source.readStatement(), null);
}
}
private String randomStatement(Random random) {
StringBuffer buff = new StringBuffer();
int len = random.nextInt(5);
for(int i=0; i<len; i++) {
switch(random.nextInt(10)) {
case 0: {
int l= random.nextInt(4);
String[] ch=new String[]{"\n", "\r", " ", "*", "a", "0"};
for(int j=0; j<l; j++) {
buff.append(ch[random.nextInt(ch.length)]);
}
break;
}
case 1: {
buff.append('\'');
int l= random.nextInt(4);
String[] ch=new String[]{";", "\n", "\r", "--", "//", "/", "-", "*", "/*", "*/", "\""};
for(int j=0; j<l; j++) {
buff.append(ch[random.nextInt(ch.length)]);
}
buff.append('\'');
break;
}
case 2: {
buff.append('"');
int l= random.nextInt(4);
String[] ch=new String[]{";", "\n", "\r", "--", "//", "/", "-", "*", "/*", "*/", "\'"};
for(int j=0; j<l; j++) {
buff.append(ch[random.nextInt(ch.length)]);
}
buff.append('"');
break;
}
case 3: {
buff.append('-');
if(random.nextBoolean()) {
String[] ch=new String[]{"\n", "\r", "*", "a", " "};
int l= 1 + random.nextInt(4);
for(int j=0; j<l; j++) {
buff.append(ch[random.nextInt(ch.length)]);
}
} else {
buff.append('-');
String[] ch=new String[]{";", "-", "//", "/*", "*/", "a"};
int l= random.nextInt(4);
for(int j=0; j<l; j++) {
buff.append(ch[random.nextInt(ch.length)]);
}
buff.append('\n');
}
break;
}
case 4: {
buff.append('/');
if(random.nextBoolean()) {
String[] ch=new String[]{"\n", "\r", "a", " ", "- "};
int l= 1 + random.nextInt(4);
for(int j=0; j<l; j++) {
buff.append(ch[random.nextInt(ch.length)]);
}
} else {
buff.append('*');
String[] ch=new String[]{";", "-", "//", "/* ", "--", "\n", "\r", "a"};
int l= random.nextInt(4);
for(int j=0; j<l; j++) {
buff.append(ch[random.nextInt(ch.length)]);
}
buff.append("*/");
}
break;
}
}
}
return buff.toString();
}
private void testCommon() throws Exception {
String s =
"a;';';\";\";--;\n;/*;\n*/;//;\na;";
StringReader reader = new StringReader(s);
ScriptReader source = new ScriptReader(reader);
check(source.readStatement(),"a");
check(source.readStatement(),"';'");
check(source.readStatement(),"\";\"");
check(source.readStatement(),"--;\n");
check(source.readStatement(),"/*;\n*/");
check(source.readStatement(),"//;\na");
check(source.readStatement(), null);
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import org.h2.security.AES;
import org.h2.security.SHA256;
import org.h2.security.XTEA;
import org.h2.test.TestBase;
import org.h2.util.ByteUtils;
/**
* @author Thomas
*/
public class TestSecurity extends TestBase {
public void test() throws Exception {
testSHA();
testAES();
testXTEA();
}
public void testSHA() throws Exception {
SHA256 sha = new SHA256();
testOneSHA(sha);
}
private String getHashString(SHA256 sha, byte[] data) {
byte[] result = sha.getHash(data);
return ByteUtils.convertBytesToString(result);
}
private void testOneSHA(SHA256 sha) throws Exception {
if (!getHashString(sha, new byte[] { })
.equals(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")) {
throw new Exception("x");
}
if (!getHashString(sha, new byte[] { 0x19 })
.equals(
"68aa2e2ee5dff96e3355e6c7ee373e3d6a4e17f75f9518d843709c0c9bc3e3d4")) {
throw new Exception("x");
}
if (!getHashString(sha, new byte[] { (byte)0xe3, (byte)0xd7, 0x25, 0x70, (byte)0xdc, (byte)0xdd, 0x78, 0x7c, (byte)0xe3, (byte)0x88, 0x7a, (byte)0xb2, (byte)0xcd, 0x68, 0x46, 0x52 })
.equals(
"175ee69b02ba9b58e2b0a5fd13819cea573f3940a94f825128cf4209beabb4e8")) {
throw new Exception("x");
}
}
public void testXTEA() throws Exception {
byte[] test = new byte[4096];
XTEA tea = new XTEA();
tea.setKey("abcdefghijklmnop".getBytes());
for (int i = 0; i < 10; i++) {
tea.decryptBlock(test, test, 0);
}
}
private void testAES() throws Exception {
AES test = new AES();
test.setKey(ByteUtils.convertStringToBytes("000102030405060708090A0B0C0D0E0F"));
byte[] in = new byte[128];
byte[] enc = new byte[128];
test.encrypt(enc, 0, 128);
test.decrypt(enc, 0, 128);
if(ByteUtils.compareNotNull(in, enc)!=0) {
throw new Error("hey!");
}
for (int i = 0; i < 10; i++) {
test.encrypt(in, 0, 128);
test.decrypt(enc, 0, 128);
}
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import org.h2.compress.LZFInputStream;
import org.h2.compress.LZFOutputStream;
import org.h2.test.TestBase;
public class TestStreams extends TestBase {
public void test() throws Exception {
testLZFStreams();
}
byte[] getRandomBytes(Random random) {
int[] sizes = new int[]{0, 1, random.nextInt(1000), random.nextInt(100000), random.nextInt(1000000)};
int size = sizes[random.nextInt(sizes.length)];
byte[] buffer = new byte[size];
if(random.nextInt(5) == 1) {
random.nextBytes(buffer);
} else if(random.nextBoolean()) {
int patternLen = random.nextInt(100)+1;
for(int j=0; j<size; j++) {
buffer[j] = (byte)(j % patternLen);
}
}
return buffer;
}
private void testLZFStreams() throws Exception {
Random random = new Random(1);
for(int i=0; i<1000; i+=3) {
byte[] buffer = getRandomBytes(random);
ByteArrayOutputStream out = new ByteArrayOutputStream();
LZFOutputStream comp = new LZFOutputStream(out);
if(random.nextInt(10) == 1) {
comp.write(buffer);
} else {
for(int j=0; j<buffer.length;) {
int[] sizes = new int[]{0, 1, random.nextInt(100), random.nextInt(100000)};
int size = sizes[random.nextInt(sizes.length)];
size = Math.min(size, buffer.length - j);
if(size == 1) {
comp.write(buffer[j]);
} else {
comp.write(buffer, j, size);
}
j+=size;
}
}
comp.close();
byte[] compressed = out.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(compressed);
LZFInputStream decomp = new LZFInputStream(in);
byte[] test = new byte[buffer.length];
for(int j=0; j<buffer.length;) {
int[] sizes = new int[]{0, 1, random.nextInt(100), random.nextInt(100000)};
int size = sizes[random.nextInt(sizes.length)];
if(size == 1) {
int x = decomp.read();
if(x < 0) {
break;
}
test[j++] = (byte)x;
} else {
size = Math.min(size, test.length-j);
int l = decomp.read(test, j, size);
if(l < 0) {
break;
} else {
j += l;
}
}
}
check(buffer, test);
}
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.util.Random;
import org.h2.test.TestBase;
import org.h2.util.StringCache;
public class TestStringCache extends TestBase {
public static void main(String[] args) throws Exception {
new TestStringCache().runBenchmark();
}
private void runBenchmark() throws Exception {
returnNew = false;
for(int i=0; i<6; i++) {
useIntern = (i % 2) == 1;
long time = System.currentTimeMillis();
testSingleThread(100000);
time = System.currentTimeMillis()-time;
System.out.println(time + " ms (useIntern=" + useIntern+")");
}
}
private Random random = new Random(1);
private String[] some = new String[] { null, "", "ABC", "this is a medium sized string", "1", "2"};
private volatile boolean stop;
private boolean returnNew;
private boolean useIntern;
public void test() throws Exception {
returnNew = true;
StringCache.clearCache();
testSingleThread(getSize(5000, 20000));
testMultiThreads();
returnNew = false;
StringCache.clearCache();
testSingleThread(getSize(5000, 20000));
testMultiThreads();
}
String randomString() {
if(random.nextBoolean()) {
String s = some[random.nextInt(some.length)];
if(s != null && random.nextBoolean()) {
s = new String(s);
}
return s;
} else {
int len = random.nextBoolean() ? random.nextInt(1000) : random.nextInt(10);
StringBuffer buff = new StringBuffer(len);
for(int i=0; i<len; i++) {
buff.append(random.nextInt(0xfff));
}
return buff.toString();
}
}
void testString() {
String a = randomString();
if(returnNew) {
String b = StringCache.getNew(a);
try {
check(a, b);
} catch (Exception e) {
e.printStackTrace();
}
if(a != null && a == b && a.length()>0) {
throw new Error("a=" + System.identityHashCode(a) + " b=" + System.identityHashCode(b));
}
} else {
String b;
if(useIntern) {
b = a == null ? null : a.intern();
} else {
b = StringCache.get(a);
}
try {
check(a, b);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void testSingleThread(int len) throws Exception {
for(int i=0; i<len; i++) {
testString();
}
}
private void testMultiThreads() throws Exception {
int threadCount = getSize(3, 100);
Thread[] threads = new Thread[threadCount];
for(int i=0; i<threadCount; i++) {
Thread t = new Thread(new Runnable() {
public void run() {
while(!stop) {
testString();
}
}
});
threads[i] = t;
}
for(int i=0; i<threadCount; i++) {
threads[i].start();
}
int wait = getSize(200, 2000);
Thread.sleep(wait);
stop = true;
for(int i=0; i<threadCount; i++) {
threads[i].join();
}
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Random;
import org.h2.test.TestBase;
import org.h2.util.StringUtils;
public class TestStringUtils extends TestBase {
public void test() throws Exception {
testXML();
testSplit();
testJavaString();
testURL();
}
private void testXML() throws Exception {
check("<!-- - - - - - -abc- - - - - - -->\n", StringUtils.xmlComment("------abc------"));
check("<test/>\n", StringUtils.xmlNode("test", null, null));
check("<test>Gr&#xfc;bel</test>\n", StringUtils.xmlNode("test", null, StringUtils.xmlText("Gr\u00fcbel")));
check("Rand&amp;Blue", StringUtils.xmlText("Rand&Blue"));
check("&lt;&lt;[[[]]]&gt;&gt;", StringUtils.xmlCData("<<[[[]]]>>"));
Date dt = StringUtils.parseDateTime("2001-02-03 04:05:06 GMT", "yyyy-MM-dd HH:mm:ss z", "en", "GMT");
String s = StringUtils.xmlStartDoc() +
StringUtils.xmlComment("Test Comment") +
StringUtils.xmlNode("rss", StringUtils.xmlAttr("version", "2.0"),
StringUtils.xmlComment("Test Comment\nZeile2") +
StringUtils.xmlNode("channel", null,
StringUtils.xmlNode("title", null, "H2 Database Engine") +
StringUtils.xmlNode("link", null, "http://www.h2database.com") +
StringUtils.xmlNode("description", null, "H2 Database Engine") +
StringUtils.xmlNode("language", null, "en-us") +
StringUtils.xmlNode("pubDate", null, StringUtils.formatDateTime(dt, "EEE, d MMM yyyy HH:mm:ss z", "en", "GMT")) +
StringUtils.xmlNode("lastBuildDate", null, StringUtils.formatDateTime(dt, "EEE, d MMM yyyy HH:mm:ss z", "en", "GMT")) +
StringUtils.xmlNode("item", null,
StringUtils.xmlNode("title", null, "New Version 0.9.9.9.9") +
StringUtils.xmlNode("link", null, "http://www.h2database.com") +
StringUtils.xmlNode("description", null,
StringUtils.xmlCData("\nNew Features\nTest\n")
)
)
)
);
check(s, "<?xml version=\"1.0\"?>\n"
+"<!-- Test Comment -->\n"
+ "<rss version=\"2.0\">\n"
+" <!--\n"
+" Test Comment\n"
+" Zeile2\n"
+" -->\n"
+" <channel>\n"
+" <title>H2 Database Engine</title>\n"
+" <link>http://www.h2database.com</link>\n"
+" <description>H2 Database Engine</description>\n"
+" <language>en-us</language>\n"
+" <pubDate>Sat, 3 Feb 2001 04:05:06 GMT</pubDate>\n"
+" <lastBuildDate>Sat, 3 Feb 2001 04:05:06 GMT</lastBuildDate>\n"
+" <item>\n"
+" <title>New Version 0.9.9.9.9</title>\n"
+" <link>http://www.h2database.com</link>\n"
+" <description>\n"
+" <![CDATA[\n"
+" New Features\n"
+" Test\n"
+" ]]>\n"
+" </description>\n"
+" </item>\n"
+" </channel>\n"
+"</rss>\n");
}
private void testURL() throws Exception {
Random random = new Random(1);
for(int i=0; i<100; i++) {
int len = random.nextInt(10);
StringBuffer buff = new StringBuffer();
for(int j=0; j<len; j++) {
if(random.nextBoolean()) {
buff.append((char)random.nextInt(0x3000));
} else {
buff.append((char)random.nextInt(255));
}
}
String a = buff.toString();
String b = URLEncoder.encode(a, "UTF-8");
String c = URLDecoder.decode(b, "UTF-8");
check(a, c);
String d = StringUtils.urlDecode(b);
check(d, c);
}
}
private void testJavaString() throws Exception {
Random random = new Random(1);
for(int i=0; i<1000; i++) {
int len = random.nextInt(10);
StringBuffer buff = new StringBuffer();
for(int j=0; j<len; j++) {
if(random.nextBoolean()) {
buff.append((char)random.nextInt(0x3000));
} else {
buff.append((char)random.nextInt(255));
}
}
String a = buff.toString();
String b = StringUtils.javaEncode(a);
String c = StringUtils.javaDecode(b);
check(a, c);
}
}
private void testSplit() throws Exception {
check(3, StringUtils.arraySplit("ABC,DEF,G\\,HI", ',', false).length);
check(StringUtils.arrayCombine(new String[]{"", " ", ","}, ','), ", ,\\,");
Random random = new Random(1);
for(int i=0; i<100; i++) {
int len = random.nextInt(10);
StringBuffer buff = new StringBuffer();
String select = "abcd,";
for(int j=0; j<len; j++) {
char c = select.charAt(random.nextInt(select.length()));
if(c == 'a') {
buff.append("\\\\");
} else if(c=='b') {
buff.append("\\,");
} else {
buff.append(c);
}
}
String a = buff.toString();
String[] b = StringUtils.arraySplit(a, ',', false);
String c = StringUtils.arrayCombine(b, ',');
check(a, c);
}
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.sql.*;
import org.h2.test.TestBase;
import org.h2.tools.Backup;
import org.h2.tools.ChangePassword;
import org.h2.tools.DeleteDbFiles;
import org.h2.tools.RunScript;
import org.h2.tools.Server;
import org.h2.util.Resources;
public class TestTools extends TestBase {
public void test() throws Exception {
deleteDb("utils");
testResourceGenerator();
testChangePassword();
testServer();
testBackupRunscript();
}
private void testBackupRunscript() throws Exception {
Class.forName("org.h2.Driver");
String url = "jdbc:h2:" + BASE_DIR+ "/utils";
String user = "sa", password = "abc";
String fileName = BASE_DIR + "/b2.sql";
Connection conn = DriverManager.getConnection(url, user, password);
conn.createStatement().execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
conn.createStatement().execute("INSERT INTO TEST VALUES(1, 'Hello')");
conn.close();
Backup.main(new String[]{"-url", url, "-user", user, "-password", password, "-script", fileName, "-options", "nodata", "compression", "lzf", "cipher", "xtea", "password", "'123'"});
DeleteDbFiles.main(new String[]{"-dir", BASE_DIR, "-db", "utils", "-quiet"});
RunScript.main(new String[]{"-url", url, "-user", user, "-password", password, "-script", fileName, "-options", "compression", "lzf", "cipher", "xtea", "password", "'123'"});
conn = DriverManager.getConnection("jdbc:h2:" + BASE_DIR+ "/utils", "sa", "abc");
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEST");
checkFalse(rs.next());
conn.close();
}
private void testResourceGenerator() throws Exception {
Resources.main(new String[]{"."});
}
private void testChangePassword() throws Exception {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:" + BASE_DIR+ "/utils;CIPHER=XTEA;STORAGE=TEXT", "sa", "abc 123");
Statement stat = conn.createStatement();
stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
conn.close();
String[] args = new String[]{"-dir", BASE_DIR, "-db", "utils", "-cipher", "XTEA", "-decrypt", "abc", "-quiet"};
ChangePassword.main(args);
args = new String[]{"-dir", BASE_DIR, "-db", "utils", "-cipher", "AES", "-encrypt", "def", "-quiet"};
ChangePassword.main(args);
conn = DriverManager.getConnection("jdbc:h2:" + BASE_DIR+ "/utils;CIPHER=AES", "sa", "def 123");
stat = conn.createStatement();
stat.execute("SELECT * FROM TEST");
conn.close();
args = new String[]{"-dir", BASE_DIR, "-db", "utils", "-quiet"};
DeleteDbFiles.main(args);
}
private void testServer() throws Exception {
Connection conn;
Server server = Server.createTcpServer(new String[]{"-ifExists", "false"}).start();
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/test", "sa", "");
conn.close();
server.stop();
server = Server.createTcpServer(new String[]{"-ifExists", "true", "-tcpPassword", "abc"}).start();
try {
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/test2", "sa", "");
error("should not be able to create new db");
} catch(SQLException e) {
checkNotGeneralException(e);
}
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/test", "sa", "");
conn.close();
try {
Server.shutdownTcpServer("tcp://localhost", "", true);
error("shouldn't work and should throw an exception");
} catch(SQLException e) {
// expected
}
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/test", "sa", "");
conn.close();
Server.shutdownTcpServer("tcp://localhost", "abc", true);
try {
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/test", "sa", "");
error("server must have been closed");
} catch(SQLException e) {
checkNotGeneralException(e);
}
}
}
/*
* Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.test.unit;
import java.sql.SQLException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Random;
import org.h2.store.DataHandler;
import org.h2.store.FileStore;
import org.h2.test.TestBase;
import org.h2.util.ObjectArray;
import org.h2.util.ValueHashMap;
import org.h2.value.CompareMode;
import org.h2.value.Value;
import org.h2.value.ValueInt;
public class TestValueHashMap extends TestBase implements DataHandler {
CompareMode compareMode = new CompareMode(null, null);
public void test() throws Exception {
ValueHashMap map = new ValueHashMap(this);
HashMap hash = new HashMap();
Random random = new Random(1);
Comparator vc = new Comparator() {
public int compare(Object o1, Object o2) {
Value v1 = (Value)o1;
Value v2 = (Value)o2;
try {
return v1.compareTo(v2, compareMode);
} catch(SQLException e) {
throw new Error(e);
}
}
};
for(int i=0; i<10000; i++) {
int op = random.nextInt(10);
Value key = ValueInt.get(random.nextInt(100));
Value value = ValueInt.get(random.nextInt(100));
switch(op) {
case 0:
map.put(key, value);
hash.put(key, value);
break;
case 1:
map.remove(key);
hash.remove(key);
break;
case 2:
Value v1 = (Value) map.get(key);
Value v2 = (Value) hash.get(key);
check((v1==null && v2==null) || v1.compareEqual(v2));
break;
case 3: {
ObjectArray a1 = map.keys();
ObjectArray a2 = new ObjectArray(hash.keySet());
check(a1.size(), a2.size());
a1.sort(vc);
a2.sort(vc);
for(int j=0; j<a1.size(); j++) {
check(((Value)a1.get(j)).compareEqual((Value)a2.get(j)));
}
break;
}
case 4:
ObjectArray a1 = map.values();
ObjectArray a2 = new ObjectArray(hash.values());
check(a1.size(), a2.size());
a1.sort(vc);
a2.sort(vc);
for(int j=0; j<a1.size(); j++) {
check(((Value)a1.get(j)).compareEqual((Value)a2.get(j)));
}
break;
}
}
}
public boolean getTextStorage() {
return false;
}
public String getDatabasePath() {
return null;
}
public FileStore openFile(String name, boolean mustExist) throws SQLException {
return null;
}
public int getChecksum(byte[] data, int start, int end) {
return 0;
}
public void checkPowerOff() throws SQLException {
}
public void checkWritingAllowed() throws SQLException {
}
public void freeUpDiskSpace() throws SQLException {
}
public void handleInvalidChecksum() throws SQLException {
}
public int compareTypeSave(Value a, Value b) throws SQLException {
return a.compareTo(b, compareMode);
}
public int getMaxLengthInplaceLob() {
return 0;
}
public int allocateObjectId(boolean b, boolean c) {
return 0;
}
public String createTempFile() throws SQLException {
return null;
}
public String getLobCompressionAlgorithm(int type) {
return null;
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论