alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 * Copyright 2001-2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.io.testtools;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Arrays;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;

import junit.framework.AssertionFailedError;
import junit.framework.TestCase;

/**
 * Base class for testcases doing tests with files.
 * 
 * @author Jeremias Maerki
 */
public abstract class FileBasedTestCase extends TestCase {

    private static File testDir;

    public FileBasedTestCase(String name) {
        super(name);
    }
    
    public static File getTestDirectory() {
        if (testDir == null) {
            testDir = (new File("test/io/")).getAbsoluteFile();
        }
        return testDir;
    }
    
    protected void createFile(File file, long size)
            throws IOException {
        if (!file.getParentFile().exists()) {
            throw new IOException("Cannot create file " + file 
                + " as the parent directory does not exist");
        }
        BufferedOutputStream output =
            new BufferedOutputStream(new java.io.FileOutputStream(file));
        try {
            generateTestData(output, size);
        } finally {
            IOUtils.closeQuietly(output);
        }
    }
    
    protected byte[] generateTestData(long size) {
        try {
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            generateTestData(baout, size);
            return baout.toByteArray();
        } catch (IOException ioe) {
            throw new RuntimeException("This should never happen: " + ioe.getMessage());
        }
    }
    
    protected void generateTestData(OutputStream out, long size) 
                throws IOException {
        for (int i = 0; i < size; i++) {
            //output.write((byte)'X');

            // nice varied byte pattern compatible with Readers and Writers
            out.write( (byte)( (i % 127) + 1) );
        }
    }

    protected File newFile(String filename) throws IOException {
        File destination = new File( getTestDirectory(), filename );
        /*
        assertTrue( filename + "Test output data file shouldn't previously exist",
                    !destination.exists() );
        */
        if (destination.exists()) {
            FileUtils.forceDelete(destination);
        }
        return destination;
    }

    protected void checkFile( File file, File referenceFile )
                throws Exception {
        assertTrue( "Check existence of output file", file.exists() );
        assertEqualContent( referenceFile, file );
    }

    /** Assert that the content of two files is the same. */
    private void assertEqualContent( File f0, File f1 )
        throws IOException
    {
        /* This doesn't work because the filesize isn't updated until the file
         * is closed.
        assertTrue( "The files " + f0 + " and " + f1 +
                    " have differing file sizes (" + f0.length() +
                    " vs " + f1.length() + ")", ( f0.length() == f1.length() ) );
        */
        InputStream is0 = new java.io.FileInputStream( f0 );
        try {
            InputStream is1 = new java.io.FileInputStream( f1 );
            try {
                byte[] buf0 = new byte[ 1024 ];
                byte[] buf1 = new byte[ 1024 ];
                int n0 = 0;
                int n1 = 0;

                while( -1 != n0 )
                {
                    n0 = is0.read( buf0 );
                    n1 = is1.read( buf1 );
                    assertTrue( "The files " + f0 + " and " + f1 +
                                " have differing number of bytes available (" + n0 +
                                " vs " + n1 + ")", ( n0 == n1 ) );

                    assertTrue( "The files " + f0 + " and " + f1 +
                                " have different content", Arrays.equals( buf0, buf1 ) );
                }
            } finally {
                is1.close();
            }
        } finally {
            is0.close();
        }
    }

    /** Assert that the content of a file is equal to that in a byte[]. */
    protected void assertEqualContent( byte[] b0, File file )
        throws IOException
    {
        InputStream is = new java.io.FileInputStream( file );
        try {
            byte[] b1 = new byte[ b0.length ];
            int numRead = is.read( b1 );
            assertTrue( "Different number of bytes", numRead == b0.length && is.available() == 0 );
            for( int i = 0;
                 i < numRead;
                 assertTrue( "Byte " + i + " differs (" + b0[ i ] + " != " + b1[ i ] + ")", 
                    b0[ i ] == b1[ i ] ), i++
                );
        } finally {
            is.close();
        }
    }

    protected void checkWrite(OutputStream output) throws Exception {
        try {
            new java.io.PrintStream(output).write(0);
        } catch (Throwable t) {
            throw new AssertionFailedError(
                "The copy() method closed the stream "
                    + "when it shouldn't have. "
                    + t.getMessage());
        }
    }

    protected void checkWrite(Writer output) throws Exception {
        try {
            new java.io.PrintWriter(output).write('a');
        } catch (Throwable t) {
            throw new AssertionFailedError(
                "The copy() method closed the stream "
                    + "when it shouldn't have. "
                    + t.getMessage());
        }
    }

    protected void deleteFile( File file )
        throws Exception {
        if (file.exists()) {
            assertTrue("Couldn't delete file: " + file, file.delete());
        }
    }
    

}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.