Package eu.bges

Source Code of eu.bges.IOUtilTests

package eu.bges;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;

import com.google.common.base.Optional;
import com.google.common.io.Files;

import eu.bges.IOUtil;
import eu.bges.JavaScriptUtil;
import eu.bges.SysUtil;
import eu.bges.SysUtil.OS;
import eu.bges.config.KeyNotFoundException;

/**
* Tests for the {@link IOUtil}.
*
* @author Matthias Braun
*
*/
public class IOUtilTests {

    private static final String ROOT_DIR_NAME = "rootDir";
    private static final String MULTILANGUAGE = "/testfiles/multilanguage.txt";
    private static final String JAVASCRIPT_JS = "/testfiles/javascript.js";
    private static final String JAVASCRIPT_JS_NAME = "javascript.js";
    private static final String CORRUPT_HTML = "/testfiles/corrupt.html";
    private static final String INVALID_PATH = "??inval:d??";
    private static final String NON_EXISTANT_FILE = "doesn't Exist";

    /**
     * A value that is set in a properties file
     */
    private static final String NEW_VAL = "'NEWVAL'";

    /**
     * A property in a property file
     */
    private static final String XML_STATE = "xmlState";

    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Rule
    public TemporaryFolder tempDir = new TemporaryFolder();

    @Test
    public void createFileAndDirByAppendingToFile() throws IOException {

        final File dir = tempDir.newFolder();
        final File dirThatShouldBeCreated = new File(dir.getAbsolutePath()
                + "/createMe/andMeToo/");
        final File fileThatShouldBeCreated = new File(
                dirThatShouldBeCreated.getAbsolutePath() + "testFile.txt");
        // The directory and the file should not exist yet
        assertFalse(dirThatShouldBeCreated.exists());
        assertFalse(fileThatShouldBeCreated.exists());
        // Write a Persian string to the file (to test UTF-8 support)
        final String input = StringUtilTests.PERSIAN_STRING;
        /*
         * The writing should also make sure that the file and its parent dirs
         * exist by creating them if they don't exist
         */
        final boolean success = IOUtil.append(input, fileThatShouldBeCreated);
        assertTrue(success);
        assertTrue(fileThatShouldBeCreated.exists());
    }

    @Test
    public void createFileAndDirByWritingToFile() throws IOException {

        final File dir = tempDir.newFolder();
        final File dirThatShouldBeCreated = new File(dir.getAbsolutePath()
                + "/createMe/andMeToo/");
        final File fileThatShouldBeCreated = new File(
                dirThatShouldBeCreated.getAbsolutePath() + "testFile.txt");
        // The directory and the file should not exist yet
        assertFalse(dirThatShouldBeCreated.exists());
        assertFalse(fileThatShouldBeCreated.exists());
        // Write a Persian string to the file (to test UTF-8 support)
        final String input = StringUtilTests.PERSIAN_STRING;
        /*
         * The writing should also make sure that the file and its parent dirs
         * exist by creating them if they don't exist
         */
        final boolean success = IOUtil.write(input, fileThatShouldBeCreated);
        assertTrue(success);
        assertTrue(fileThatShouldBeCreated.exists());
    }

    @Test
    public void createFileByWritingToIt() throws IOException {

        final File file = tempDir.newFile();

        // Test with non-ascii input
        final String input = StringUtilTests.PERSIAN_STRING;
        final boolean success = IOUtil.write(input, file);
        assertTrue(success);
        assertTrue(file.exists());
    }

    @Test
    public void deleteDirWithFiles() throws IOException {

        // Create a directory that is considered to be at the root level
        final File rootDir = tempDir.newFolder(ROOT_DIR_NAME);
        final File rootFile = new File(rootDir, "root.txt");
        Files.touch(rootFile);
        assertTrue("Root level file should exist", rootFile.exists());

        // Create a sub folder with a file in it
        final File subDir = new File(rootDir, "subDir");
        final boolean createdSubDir = subDir.mkdir();
        assertTrue(
                "Sub dir was not created successfully (does it exist already?)",
                createdSubDir);
        final File subFile = new File(subDir, "sub.txt");
        Files.touch(subFile);
        assertTrue("Sub level file should exist", subFile.exists());

        IOUtil.deleteRecursively(rootDir);
        assertFalse("Root dir should not exist anymore", rootDir.exists());
    }

    @Test
    public void deleteEmptyDir() throws IOException {

        final File emptyDir = tempDir.newFolder();
        assertTrue(emptyDir.exists());
        IOUtil.deleteRecursively(emptyDir);
        assertFalse("Empty dir should not exist anymore", emptyDir.exists());
    }

    /**
     * Get the value of a variable from a JavaScript config file. Then set a new
     * value and read that value from the file to see if it was really set.
     * Afterwards restore the old value.
     *
     * @throws KeyNotFoundException
     */
    @Test
    public void getAndSetVariableInFile() throws KeyNotFoundException {

        final File configFile = IOUtil.getResource(JAVASCRIPT_JS, getClass());
        final String oldVal = IOUtil.getVal(XML_STATE, configFile,
                JavaScriptUtil.JS_PATTERN);
        assertFalse("The new value (" + NEW_VAL
                + ") should be different than the old one",
                oldVal.equals(NEW_VAL));
        final boolean success = IOUtil.setVal(XML_STATE, NEW_VAL, configFile,
                JavaScriptUtil.JS_PATTERN);
        assertTrue(success);
        final String newVal = IOUtil.getVal(XML_STATE, configFile,
                JavaScriptUtil.JS_PATTERN);

        assertTrue("The value that was set (" + NEW_VAL
                + ") differs from that one which was read (" + newVal + ")",
                newVal.equals(NEW_VAL));
        // Restore the original state of the file
        final boolean restoreSuccess = IOUtil.setVal(XML_STATE, oldVal,
                configFile, JavaScriptUtil.JS_PATTERN);
        assertTrue(restoreSuccess);

    }

    @Test
    public void getCharCount() throws IOException {

        final File file = tempDir.newFile();

        final String content = "let's count some characters";
        IOUtil.write(content, file);
        final int charCount = IOUtil.getCharCount(file);
        assertEquals(charCount, content.length());
    }

    @Test
    public void getFileName() {
        final URL configFile = IOUtilTests.class.getResource(JAVASCRIPT_JS);
        final String fileName = IOUtil.getFileName(configFile);

        assertEquals(fileName, JAVASCRIPT_JS_NAME);
    }

    @Test
    public void getFilesInDirNonRecursively() {
        final Path currDir = IOUtil.getCurrDir();
        final boolean recursive = false;
        final List<Path> filepaths = IOUtil.listFiles(currDir, recursive);
        assertFalse("There should be files in the current directory: "
                + currDir, filepaths.isEmpty());
    }

    @Test
    public void getFilesInDirRecursively() {
        final Path currDir = IOUtil.getCurrDir();
        final boolean recursive = true;
        final List<Path> filepaths = IOUtil.listFiles(currDir, recursive);
        assertFalse("There should be files in the current directory: "
                + currDir, filepaths.isEmpty());
    }

    @Test
    public void getNameOfFileThatDoesntExist() {
        final String fileName = IOUtil.getFileName(INVALID_PATH);
        assertEquals(fileName, INVALID_PATH);
    }

    @Test
    public void getParentForWinRoot() {
        final File rootDir = getRootDir();
        assertTrue(rootDir + " should exist as a directory", rootDir.exists());
        assertFalse(rootDir + " should have no parent",
                IOUtil.getParent(rootDir).isPresent());
    }

    @Test
    public void getParentNonExistantInputFile() {
        final File file = new File(NON_EXISTANT_FILE);
        final Optional<String> parentMaybe = IOUtil.getParent(file);
        assertFalse("Non existant file has no parent", parentMaybe.isPresent());
    }

    @Test
    public void getParentNullInputFile() {
        final Optional<String> parentMaybe = IOUtil.getParent(null);
        assertFalse("Null has no parent", parentMaybe.isPresent());
    }

    @Test
    public void getParentValidInputDir() throws IOException {
        final File rootDir = tempDir.newFolder(ROOT_DIR_NAME);

        // Create a sub folder
        final File subDir = new File(rootDir, "subDir");
        final boolean createdSubDir = subDir.mkdir();
        assertTrue(
                "Sub dir was not created successfully (does it exist already?)",
                createdSubDir);
        final Optional<String> parentMaybe = IOUtil.getParent(subDir);
        assertTrue("There should be a parent to the directory",
                parentMaybe.isPresent());

        // The parent exists -> Check if it has the correct path
        assertEquals("The parent path returned is not correct",
                parentMaybe.get(), rootDir.toString());

    }

    @Test
    public void getParentValidInputFile() throws IOException {
        final File rootDir = tempDir.newFolder(ROOT_DIR_NAME);
        final File rootFile = new File(rootDir, "root.txt");
        Files.touch(rootFile);
        assertTrue("Root level file should exist", rootFile.exists());
        final Optional<String> parentMaybe = IOUtil.getParent(rootFile);
        assertTrue("There should be a parent to the file",
                parentMaybe.isPresent());

        // The parent exists -> Check if it has the correct path
        assertEquals("The parent path returned is not correct",
                parentMaybe.get(), rootDir.toString());
    }

    @Test
    public void getResourceAsFile() {
        final File f = IOUtil.getResource(JAVASCRIPT_JS, getClass());
        assertTrue(f.exists());
    }

    @Test
    public void getResourceOfNonExistantFile() {
        final File f = IOUtil.getResource(INVALID_PATH, getClass());
        assertFalse(f.exists());
    }

    @Test
    public void getVarFromCorruptFile() throws KeyNotFoundException {
        final File corruptFile = IOUtil.getResource(CORRUPT_HTML, getClass());
        exception.expect(KeyNotFoundException.class);
        IOUtil.getVal(XML_STATE, corruptFile, JavaScriptUtil.JS_PATTERN);

    }

    @Test
    public void joinValidPaths() {
        final String path1 = ROOT_DIR_NAME;
        final String path2 = MULTILANGUAGE;
        final File joinedPaths = IOUtil.join(path1, path2);
        assertTrue(joinedPaths.toString().length() >= ROOT_DIR_NAME.length()
                + MULTILANGUAGE.length());
    }

    @Test
    public void makeDir() {
        final Path currDir = IOUtil.getCurrDir();
        IOUtil.makeDir(currDir.toString());
        final String fileName = IOUtil.getFileName(INVALID_PATH);
        assertEquals(fileName, INVALID_PATH);
    }

    @Test
    public void makeDirWithBadInput() {
        final boolean newDirWasCreated = IOUtil.makeDir(null);
        assertFalse(newDirWasCreated);
    }

    @Test
    public void parseVarsFromCorruptFile() {
        final String corruptFilePath = IOUtilTests.class.getResource(
                CORRUPT_HTML).getPath();
        final Map<String, String> parsedMap = IOUtil.parseVarsFromFile(
                new File(corruptFilePath), JavaScriptUtil.JS_PATTERN);
        assertTrue("Parsed map should be empty (file was corrupt)",
                parsedMap.isEmpty());
    }

    @Test
    public void parseVarsFromNonExistantFile() {
        final Map<String, String> parsedMap = IOUtil.parseVarsFromFile(
                new File(INVALID_PATH), JavaScriptUtil.JS_PATTERN);
        assertTrue("Parsed map should be empty (file didn't exist)",
                parsedMap.isEmpty());
    }

    @Test
    public void readCorruptFile() {

        final File corruptFile = IOUtil.getResource(CORRUPT_HTML, getClass());
        final String content = IOUtil.read(corruptFile);
        assertFalse(content.isEmpty());
    }

    @Test
    public void readMultilanguageFile() {
        final File multilangFile = IOUtil.getResource(MULTILANGUAGE,
                getClass());
        final String content = IOUtil.read(multilangFile);
        assertFalse(content.isEmpty());
    }

    @Test
    public void toPath() {
        final String pathStrInput = tempDir.getRoot().getAbsolutePath();
        final Path path = IOUtil.toPath(pathStrInput);
        final String absPathOutput = path.toFile().getAbsolutePath();
        assertEquals(pathStrInput, absPathOutput);
    }

    @Test
    public void toPathWithInvalidPath() {
        /*
         * Only on Windows FileUtil.toPath throws an InvalidPathException when
         * forbidden characters are used in the file name -> 'assumeTrue' only
         * executes the test if it's run on Windows
         */
        assumeTrue(SysUtil.getOS().equals(OS.WINDOWS));

        final String pathStrInput = INVALID_PATH;
        exception.expect(InvalidPathException.class);
        IOUtil.toPath(pathStrInput);
    }

    @Test
    public void toPathWithNonExistingFile() {
        final String pathStrInput = new File(NON_EXISTANT_FILE)
        .getAbsolutePath();
        final Path path = IOUtil.toPath(NON_EXISTANT_FILE);
        final String absPathOutput = path.toFile().getAbsolutePath();
        assertEquals(pathStrInput, absPathOutput);
    }

    /**
     * @return A root directory of the file system. Should work system
     *         independently.
     */
    private File getRootDir() {
        return File.listRoots()[0];
    }
}
TOP

Related Classes of eu.bges.IOUtilTests

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.