View Javadoc
1   package io.guixer.tools;
2   
3   import static com.google.common.base.Preconditions.checkNotNull;
4   import static org.apache.commons.lang3.StringUtils.isBlank;
5   
6   import java.io.FileNotFoundException;
7   import java.io.IOException;
8   import java.io.InputStream;
9   import java.util.Properties;
10  
11  import javax.annotation.Nullable;
12  
13  public abstract class TestUtils {
14  
15  	private static final String TEST_PROPERTIES_FILE_NAME = "test.properties";
16  
17  	public static Properties getTestProperties() throws IOException {
18  
19  		final Properties properties = new Properties();
20  
21  		final InputStream is = Thread.currentThread().getContextClassLoader()
22  				.getResourceAsStream(TEST_PROPERTIES_FILE_NAME);
23  
24  		if (is == null) {
25  
26  			throw new FileNotFoundException("Resource not found: " + TEST_PROPERTIES_FILE_NAME);
27  		}
28  
29  		try {
30  
31  			properties.load(is);
32  
33  		} finally {
34  
35  			is.close();
36  		}
37  
38  		return properties;
39  	}
40  
41  	public static String getTestProperty(
42  		final String name
43  	) throws IOException {
44  
45  		return getTestPropertyOrDefaultValue(name, null, false);
46  	}
47  
48  	private static String getTestPropertyOrDefaultValue(
49  		final String name,
50  		@Nullable final String defaultValue,
51  		final boolean nullable
52  	) throws IOException {
53  
54  		checkNotNull(name, "name");
55  
56  		final Properties properties = getTestProperties();
57  
58  		final String value = properties.getProperty(name);
59  
60  		if (isBlank(value)) {
61  
62  			if (!nullable && defaultValue == null) {
63  
64  				System.err.println("No value found for property: \"" + name + "\"");
65  
66  				System.err.println("Make sure the property is set in the \"" + TEST_PROPERTIES_FILE_NAME + "\" file.");
67  
68  				throw new RuntimeException("No value found for property: \"" + name + "\"");
69  
70  			} else {
71  
72  				return defaultValue;
73  			}
74  		}
75  
76  		if (value.contains("$")) {
77  
78  			System.err.println("Value has not been processed for property: \"" + name + "\": \"" + value + "\"");
79  
80  			System.err.println("Make sure to run \"mvn process-test-resources\" to process the \""
81  					+ TEST_PROPERTIES_FILE_NAME + "\" file, prior to running the tests.");
82  
83  			throw new RuntimeException(
84  					"Value has not been processed for property: \"" + name + "\": \"" + value + "\"");
85  		}
86  
87  		return value;
88  	}
89  
90  	public static String getTestProperty(
91  		final String name,
92  		final String defaultValue
93  	) throws IOException {
94  
95  		checkNotNull(defaultValue, "defaultValue");
96  
97  		return getTestPropertyOrDefaultValue(name, defaultValue, false);
98  	}
99  
100 	public static String getTestPropertyOrNull(
101 		final String name
102 	) throws IOException {
103 
104 		return getTestPropertyOrDefaultValue(name, null, true);
105 	}
106 }