⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 testbase.java

📁 非常棒的java数据库
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
 * (license2)
 * Initial Developer: H2 Group
 */
package org.h2.test;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Properties;

import org.h2.jdbc.JdbcConnection;
import org.h2.message.TraceSystem;
import org.h2.store.FileLock;
import org.h2.tools.DeleteDbFiles;

/**
 * The base class for all tests.
 */
public abstract class TestBase {

    // private static final String BASE_TEST_DIR = 
    // System.getProperty("java.io.tmpdir") + "/h2";
    private static final String BASE_TEST_DIR = "data";
    
    public static String getTestDir(String name) {
        return BASE_TEST_DIR + "/test" + name;
    }
    
    protected static String baseDir = getTestDir("");

    protected TestAll config;
    private long start;

    protected void startServerIfRequired() throws SQLException {
        config.beforeTest();
    }

    public TestBase init(TestAll conf) throws Exception {
        baseDir = getTestDir("");
        this.config = conf;
        return this;
    }

    public void testCase(int i) throws Exception {
        // do nothing
    }

    public void runTest(TestAll conf) {
        try {
            init(conf);
            start = System.currentTimeMillis();
            test();
            println("");
        } catch (Exception e) {
            fail("FAIL " + e.toString(), e);
            if (config.stopOnError) {
                throw new Error("ERROR");
            }
        }
    }

    public Connection getConnection(String name) throws Exception {
        return getConnectionInternal(getURL(name, true), getUser(), getPassword());
    }

    protected Connection getConnection(String name, String user, String password) throws Exception {
        return getConnectionInternal(getURL(name, false), user, password);
    }

    protected String getPassword() {
        return "123";
    }

    private void deleteIndexFiles(String name) throws SQLException {
        if (name.indexOf(";") > 0) {
            name = name.substring(0, name.indexOf(';'));
        }
        name += ".index.db";
        if (new File(name).canWrite()) {
            new File(name).delete();
        }
    }

    protected String getURL(String name, boolean admin) throws SQLException {
        String url;
        if (name.startsWith("jdbc:")) {
            return name;
        }
        if (config.memory) {
            url = "mem:" + name;
        } else {
            if (!name.startsWith("memFS:") && !name.startsWith(baseDir + "/")) {
                name = baseDir + "/" + name;
            }
            if (config.deleteIndex) {
                deleteIndexFiles(name);
            }
            if (config.networked) {
                if (config.ssl) {
                    url = "ssl://localhost:9192/" + name;
                } else {
                    url = "tcp://localhost:9192/" + name;
                }
            } else {
                url = name;
            }
            if (config.traceSystemOut) {
                url += ";TRACE_LEVEL_SYSTEM_OUT=2";
            }
            if (config.traceLevelFile > 0 && admin) {
                url += ";TRACE_LEVEL_FILE=" + config.traceLevelFile;
            }
        }
        if (config.throttle > 0) {
            url += ";THROTTLE=" + config.throttle;
        }
        if (config.textStorage) {
            url += ";STORAGE=TEXT";
        }
        url += ";LOCK_TIMEOUT=50";
        if (admin) {
            url += ";LOG=" + config.logMode;
        }
        if (config.smallLog && admin) {
            url += ";MAX_LOG_SIZE=1";
        }
        if (config.diskUndo && admin) {
            url += ";MAX_MEMORY_UNDO=3";
        }
        if (config.big && admin) {
            // force operations to disk
            url += ";MAX_OPERATION_MEMORY=1";
        }
        if (config.mvcc) {
            url += ";MVCC=TRUE";
        }
        if (config.cache2Q) {
            url += ";CACHE_TYPE=TQ";
        }
        if (config.diskResult && admin) {
            url += ";MAX_MEMORY_ROWS=100;CACHE_SIZE=0";
        }
        return "jdbc:h2:" + url;
    }

    private Connection getConnectionInternal(String url, String user, String password) throws Exception {
        Class.forName("org.h2.Driver");
        // url += ";DEFAULT_TABLE_TYPE=1";
        // Class.forName("org.hsqldb.jdbcDriver");
        // return DriverManager.getConnection("jdbc:hsqldb:" + name, "sa", "");
        Connection conn;
        if (config.cipher != null) {
            url += ";cipher=" + config.cipher;
            password = "filePassword " + password;
            Properties info = new Properties();
            info.setProperty("user", user);
            info.setProperty("password", password);
            // a bug in the PostgreSQL driver: throws a NullPointerException if we do this
            // info.put("password", password.toCharArray());
            conn = DriverManager.getConnection(url, info);
        } else {
            conn = DriverManager.getConnection(url, user, password);
        }
        return conn;
    }

    protected int getSize(int small, int big) throws Exception {
        return config.endless ? Integer.MAX_VALUE : config.big ? big : small;
    }

    protected String getUser() {
        return "sa";
    }

    protected void trace(int x) {
        trace("" + x);
    }

    public void trace(String s) {
        if (config.traceTest) {
            println(s);
        }
    }

    protected void traceMemory() {
        if (config.traceTest) {
            trace("mem=" + getMemoryUsed());
        }
    }

    public void printTimeMemory(String s, long time) {
        if (config.big) {
            println(getMemoryUsed() + " MB: " + s);
        }
    }

    public static int getMemoryUsed() {
        Runtime rt = Runtime.getRuntime();
        long memory = Long.MAX_VALUE;
        for (int i = 0; i < 8; i++) {
            rt.gc();
            long memNow = rt.totalMemory() - rt.freeMemory();
            if (memNow >= memory) {
                break;
            }
            memory = memNow;
        }
        int mb = (int) (memory / 1024 / 1024);
        return mb;
    }

    protected void error() throws Exception {
        error("Unexpected success");
    }

    protected void error(String string) throws Exception {
        println(string);
        throw new Exception(string);
    }

    protected void fail(String s, Throwable e) {
        println(s);
        logError(s, e);
    }

    public static void logError(String s, Throwable e) {
        if (e == null) {
            e = new Exception(s);
        }
        System.out.println("ERROR: " + s + " " + e.toString() + " ------------------------------");
        e.printStackTrace();
        try {
            TraceSystem ts = new TraceSystem(null, false);
            FileLock lock = new FileLock(ts, 1000);
            lock.lock("error.lock", false);
            FileWriter fw = new FileWriter("ERROR.txt", true);
            PrintWriter pw = new PrintWriter(fw);
            e.printStackTrace(pw);
            pw.close();
            fw.close();
            lock.unlock();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    protected void println(String s) {
        long time = System.currentTimeMillis() - start;
        printlnWithTime(time, getClass().getName() + " " + s);
    }

    static void printlnWithTime(long time, String s) {
        String t = "0000000000" + time;
        t = t.substring(t.length() - 6);
        System.out.println(t + " " + s);
    }

    protected void printTime(String s) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        println(dateFormat.format(new java.util.Date()) + " " + s);
    }

    protected void deleteDb(String name) throws Exception {
        DeleteDbFiles.execute(baseDir, name, true);
    }

    protected void deleteDb(String dir, String name) throws Exception {
        DeleteDbFiles.execute(dir, name, true);
    }

    public abstract void test() throws Exception;

    public void check(int a, int b) throws Exception {
        if (a != b) {
            error("int a: " + a + " b: " + b);
        }
    }

    protected void check(byte[] a, byte[] b) throws Exception {
        check(a.length == b.length);
        for (int i = 0; i < a.length; i++) {
            if (a[i] != b[i]) {
                error("byte[" + i + "]: a=" + (int) a[i] + " b=" + (int) b[i]);
            }
        }
    }

    protected void check(String a, String b) throws Exception {
        if (a == null && b == null) {
            return;
        } else if (a == null || b == null) {
            error("string a: " + a + " b: " + b);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -