testtexttable.java

来自「纯Java的数据库」· Java 代码 · 共 460 行 · 第 1/2 页

JAVA
460
字号
            new String[] { "\"", "\\quote" },            new String[] { " ", "\\space" },            new String[] { "'", "\\apos" },            //new String[] { "\n", "\\n" },                // doesn't work as expected - seems I don't understand how this is intended to work?            new String[] { "\t", "\\t" },            new String[] { "\\", "\\" },            // some arbitrary separators which need not to be escaped            new String[] { ".", "." },            new String[] { "-", "-" },            new String[] { "#", "#" },            new String[] { ",", "," }            // unicode character            //new String[] { "\u1234", "\\u1234" }                // doesn't work. How do I specify in a FileOutputStream which encoding to use when writing                // strings?        };        for ( int i=0; i<separators.length; ++i )        {            String separator = separators[i][0];            String separatorSpec = separators[i][1];            // create the file            String tableName = "customers_" + i;            TextTableDescriptor tempCustomersDesc = new TextTableDescriptor(                tableName, m_customers.getColumnSpec(), separator, separatorSpec, m_customers.getData() );            tempCustomersDesc.createTextFile();            try {                tempCustomersDesc.createTable(m_connection);            }            catch (Throwable t) {                fail("checkSeparators: separator '" + separatorSpec + "' doesn't work: " + t.toString());            }            executeStatement("SET TABLE \"" + tableName + "\" SOURCE OFF");            executeStatement("DROP TABLE \"" + tableName + "\"" );        }    }    /** verifies the content of a given table is as expected     *  @param tableName     *      the name of the table whose content is to check     *  @param expectedValues     *      the values expected in the table     */    private void verifyTableContent(String tableName, Object[][] expectedValues) {        String selectStmt = "SELECT * FROM \"" + tableName + "\" ORDER BY ID";        try        {            java.sql.ResultSet results = m_statement.executeQuery(selectStmt);            int row = 0;            while (results.next()) {                row = results.getRow();                Object[] expectedRowContent = expectedValues[row-1];                for (int col=0; col<expectedRowContent.length; ++col)                {                    Object expectedValue = expectedRowContent[col];                    Object foundValue = results.getObject(col+1);                    assertEquals( "table " + tableName + ", row " + row + ", column " + col + ":",                        expectedValue, foundValue );                }            }            // finally ensure that there are not more rows in the table than expected            assertEquals("table " + tableName + "'s row count: ", expectedValues.length, row);        }        catch(junit.framework.AssertionFailedError e) {            throw e;        }        catch (Throwable t) {            fail("verifyTableContent(" + tableName + ") failed with " + t.toString());        }    }    /**     * executes a given m_statement     *     *  <p>Basically, this method calls <code>m_statement.execute(sql)</code>,     *  but wraps any <code>SQLException</code>s into a JUnit error.     */    private void executeStatement(String sql) {        try {            m_statement.execute(sql);        } catch (SQLException ex)  {            fail(ex.toString());        }    }    /** verifies the initial content of the "products" text table, plus a simple insertion     */    private void verifyInitialContent() {        verifyTableContent(m_products.getName(), m_products.getData());        verifyTableContent(m_customers.getName(), m_customers.getData());    }    /** does some very basic insertion tests     */    private void checkInsertions() {        // check whether inserting a value succeeds        executeStatement( "INSERT INTO \"" + m_products.getName() + "\" VALUES ( 3, 'Pears' )" );        verifyTableContent( m_products.getName(),            m_products.appendRowData( new Object[] { new Integer( 3 ), "Pears" } ) );        // check whether the PK constraint works        try {            m_statement.execute( "INSERT INTO \"" + m_products.getName() + "\" VALUES ( 1, 'Green Apples' )" );            fail( "PKs do not work as expected." );        }        catch (SQLException e) { }    }    /** verifies whether implicit and explicit dis/connections from/to the text table source work     *  as expected     */    private void checkSourceConnection() {        String sqlSetTable = "SET TABLE \"" + m_products.getName() + "\"";        // preconditions for the following tests        assertEquals("internal error: retrieving the data source does not work properly at all.",            m_products.getDataSourceSpec(), getDataSourceSpec(m_products.getName()));        assertFalse("internal error: table should not be read-only, initially", isReadOnly(m_products.getName()));        // disconnect, see if the table behaves well afterwards        executeStatement( sqlSetTable + " SOURCE OFF" );        assertEquals("Disconnecting a text table should not reset the table source.",            m_products.getDataSourceSpec(), getDataSourceSpec(m_products.getName()));        assertTrue("Disconnecting from the table source should put the table into read-only mode.",            isReadOnly(m_products.getName()));        try {            java.sql.ResultSet tableContent = m_statement.executeQuery(                "SELECT * FROM \"" + m_products.getName() + "\"" );            assertFalse("A disconnected table should be empty.", tableContent.next());        } catch (SQLException ex) {            fail("Selecting from a disconnected table should return an empty result set.");        }        // reconnect, see if the table works as expected then        executeStatement( sqlSetTable + " SOURCE ON" );        verifyTableContent( m_products.getName(), m_products.getData() );        // check whether dis-/reconnecting a readonly table preserves the readonly-ness        executeStatement( sqlSetTable + " READONLY TRUE" );        assertTrue("Setting the table to read-only failed.", isReadOnly(m_products.getName()));        executeStatement( sqlSetTable + " SOURCE OFF" );        assertTrue("Still, a disconnected table should be read-only.", isReadOnly(m_products.getName()));        executeStatement( sqlSetTable + " SOURCE ON" );        assertTrue("A reconnected readonly table should preserve its readonly-ness.", isReadOnly(m_products.getName()));        executeStatement( sqlSetTable + " READONLY FALSE" );        assertFalse("Unable to reset the readonly-ness.", isReadOnly(m_products.getName()));        // check whether setting an invalid data source sets the table to readonly, by        // preserving the data source        try        {            // create a malformed file            String fileName = "malformed.csv";            PrintStream textFile = new PrintStream(FileUtil.getDefaultInstance().openOutputStreamElement(fileName));            textFile.println("not a number;some text");            textFile.close();            new java.io.File(fileName).deleteOnExit();            // try setting it as source            String newDataSourceSpec = fileName + ";encoding=UTF-8;fs=\\semi";            try {                m_statement.execute( sqlSetTable + " SOURCE \"" + newDataSourceSpec + "\"" );                fail("a malformed data source was accepted silently.");            }            catch(java.sql.SQLException es) { /* that's expected here */ }            assertTrue("A table with an invalid data source should fall back to read-only.",                isReadOnly(m_products.getName()));            assertEquals("A data source which cannot be set should nonetheless be remembered.",                newDataSourceSpec, getDataSourceSpec(m_products.getName()));            // the data source spec should even survive a shutdown            executeStatement("SHUTDOWN");            m_connection = newConnection();            m_statement  = m_connection.createStatement();            assertEquals("A data source pointing to a mailformed file should survive a database shutdown.",                newDataSourceSpec, getDataSourceSpec(m_products.getName()));            assertTrue("After shutdown and DB-reconnect, the table with a malformed source should be read-only, again.",                isReadOnly(m_products.getName()));            // reconnect after fixing the file            textFile = new PrintStream(FileUtil.getDefaultInstance().openOutputStreamElement(fileName));            textFile.println("1;some text");            textFile.close();            executeStatement( sqlSetTable + " SOURCE ON" );            assertFalse("The file was fixed, reconnect was successful, so the table shouldn't be read-only.",                isReadOnly(m_products.getName()));            // finally re-create the proper version of the table for any further tests            m_products.createTextFile();            m_products.createTable(m_connection);            verifyTableContent(m_products.getName(), m_products.getData());        }        catch(junit.framework.AssertionFailedError e) {            throw e;        }        catch (Throwable t) {            fail("checkSourceConnection: unable to check invalid data sources, error: " + t.toString());        }    }    /** basic tests for text files     */    public void testTextFiles() {        verifyInitialContent();        checkInsertions();        checkSeparators();        checkSourceConnection();    }    public static void main(String[] argv) {        runWithResult(TestTextTable.class, "testTextFiles");    }}

⌨️ 快捷键说明

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