001package org.unix4j.util;
002
003
004import java.io.File;
005import java.net.URL;
006
007public class FileTestUtils {
008    public static File getTestFile(Class<?> testClass, String fileName) {
009        final StackTraceElement stackTraceElement = StackTraceUtil.getCurrentMethodStackTraceElement(1);
010        return getTestFile(testClass, stackTraceElement.getMethodName(), fileName);
011
012    }
013
014    public static File getTestFile(Class<?> testClass, String testMethod, String fileName) {
015        return getTestFile(testClass, testMethod, fileName, null);
016    }
017
018    public static File getTestFile(Class<?> testClass, String testMethod, String fileName, String defaultFileName) {
019        return(getTestFile(getTestDir(testClass), testMethod, fileName, defaultFileName));
020    }
021
022    public static File getTestFile(File parentDir, String testMethod, String fileName, String defaultFileName) {
023        File file;
024        if (OS.Windows.isCurrent()) {
025            file = (file = new File(parentDir, fileName + ".win")).exists() ? file : new File(parentDir, fileName);
026        } else {
027            file = new File(parentDir, fileName);
028        }
029        if (!file.exists()) {
030            if (defaultFileName == null) {
031                throw new IllegalArgumentException("test file for " + parentDir.getName() + "." + testMethod + " not found, expected file: " + fileName);
032            }
033            file = new File(parentDir, defaultFileName);
034            if (!file.exists()) {
035                throw new IllegalArgumentException("test file for " + parentDir.getName() + "." + testMethod + " not found, expected file: " + fileName + " or default file: " + defaultFileName);
036            }
037        }
038        return file;
039    }
040
041    public static File getTestDir(Class<?> testClass){
042        final String testDir = "/" + getTestDirRelativeToPackageDir(testClass);
043        URL fileURL = testClass.getResource(testDir);
044        if(fileURL == null){
045            throw new IllegalArgumentException("Test directory does not exist.  Please ensure it exists at [" + testDir + "]");
046        }
047        return new File(fileURL.getFile());
048    }
049
050    private static String getTestDirRelativeToPackageDir(Class<?> testClass) {
051        final String packageDir = testClass.getPackage().getName().replace('.', '-');
052        return packageDir + "/" + testClass.getSimpleName();
053    }
054}