Skip to content

Commit 5213788

Browse files
committed
chore: Rewrite temp configuration test code
1 parent a017117 commit 5213788

File tree

3 files changed

+96
-99
lines changed

3 files changed

+96
-99
lines changed

src/test/java/org/datadog/jmxfetch/TestCommon.java

Lines changed: 46 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,9 @@
66

77
import com.beust.jcommander.JCommander;
88

9-
import java.io.BufferedWriter;
10-
import java.io.FileInputStream;
11-
import java.io.FileNotFoundException;
12-
import java.io.FileWriter;
13-
import java.io.IOException;
9+
import java.io.*;
1410
import java.lang.management.ManagementFactory;
11+
import java.nio.charset.StandardCharsets;
1512
import java.nio.file.Files;
1613
import java.nio.file.Path;
1714
import java.util.ArrayList;
@@ -33,27 +30,29 @@
3330
import org.datadog.jmxfetch.util.CustomLogger;
3431
import org.datadog.jmxfetch.util.MetricsAssert;
3532
import org.datadog.jmxfetch.util.LogLevel;
33+
import org.junit.Rule;
34+
import org.junit.rules.TemporaryFolder;
3635

36+
/**
37+
* Config utility
38+
*/
3739
final class ConfigUtil {
38-
public static Path writeConfigYamlToTemp(String content, String yamlName) throws IOException {
39-
Path tempDirectory = Files.createTempDirectory("temp-dir");
40-
// Create a temporary file within the temporary directory
41-
Path tempFile = Files.createTempFile(tempDirectory, yamlName, ".yaml");
40+
public final Path tempConfdDir;
4241

43-
// Write the contents of the file to the temporary file
44-
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile.toFile()));
45-
writer.write(content);
46-
writer.close();
47-
48-
return tempFile;
42+
public ConfigUtil(File file) {
43+
this.tempConfdDir = file.toPath();
4944
}
5045

51-
public static String concatWithNewlines(String... lines) {
52-
StringBuilder sb = new StringBuilder();
53-
for (String line : lines) {
54-
sb.append(line).append(System.lineSeparator());
46+
public Path makeTempYamlConfigFile(String yamlName, List<String> lines) {
47+
try {
48+
return Files.write(
49+
Files.createTempFile(tempConfdDir, yamlName, ".yaml"),
50+
lines,
51+
StandardCharsets.UTF_8
52+
);
53+
} catch (IOException e) {
54+
throw new UncheckedIOException(e);
5555
}
56-
return sb.toString();
5756
}
5857
}
5958

@@ -66,9 +65,12 @@ public class TestCommon {
6665
List<Map<String, Object>> metrics = new ArrayList<>();
6766
List<Map<String, Object>> serviceChecks;
6867

68+
@Rule
69+
public TemporaryFolder temporaryFolder = new TemporaryFolder();
70+
6971
/** Setup logger. */
7072
@BeforeClass
71-
public static void init() throws Exception {
73+
public static void init() {
7274
String level = System.getProperty("tests.log_level");
7375
if (level == null) {
7476
level = "ALL";
@@ -132,10 +134,7 @@ protected void initApplication(String yamlFileName, String autoDiscoveryPipeFile
132134
// We initialize the main app that will collect these metrics using JMX
133135
String confdDirectory =
134136
Thread.currentThread().getContextClassLoader().getResource(yamlFileName).getPath();
135-
confdDirectory =
136-
new String(
137-
confdDirectory.substring(
138-
0, confdDirectory.length() - yamlFileName.length()));
137+
confdDirectory = confdDirectory.substring(0, confdDirectory.length() - yamlFileName.length());
139138
List<String> params = new ArrayList<String>();
140139
boolean sdEnabled = (autoDiscoveryPipeFile.length() > 0);
141140
params.add("--reporter");
@@ -154,7 +153,7 @@ protected void initApplication(String yamlFileName, String autoDiscoveryPipeFile
154153
params.add(5, "/foo"); // could be anything we're stubbing it out
155154
params.add(6, "--sd_enabled");
156155
}
157-
new JCommander(appConfig, params.toArray(new String[params.size()]));
156+
new JCommander(appConfig, params.toArray(new String[0]));
158157

159158
if (sdEnabled) {
160159
String autoDiscoveryPipe =
@@ -179,7 +178,7 @@ protected void initApplication(String yamlFileName, String autoDiscoveryPipeFile
179178
app.init(false);
180179
}
181180

182-
protected void initApplication(String yamlFileName) throws FileNotFoundException, IOException {
181+
protected void initApplication(String yamlFileName) throws IOException {
183182
initApplication(yamlFileName, "");
184183
}
185184

@@ -188,31 +187,37 @@ protected void initApplication(String yamlFileName) throws FileNotFoundException
188187
* The configuration can be specified as a yaml literal with each arg
189188
* representing one line of the Yaml file
190189
* Does not support any SD/AD features.
190+
*
191+
* @param yamlConfigContents the YAML configuration contents, each representing a configuration file
191192
*/
192-
protected void initApplicationWithYamlLines(String... yamlLines)
193-
throws IOException {
194-
String yamlConfig = ConfigUtil.concatWithNewlines(yamlLines);
195-
Path tempFile = ConfigUtil.writeConfigYamlToTemp(yamlConfig, "config");
193+
protected void initApplicationWithYamlLines(Path... yamlConfigs) {
194+
if (yamlConfigs == null || yamlConfigs.length == 0) {
195+
throw new IllegalArgumentException("yamlConfigContents cannot be null or empty");
196+
}
196197

197-
String confdDirectory = tempFile.getParent().toString();
198-
String yamlFileName = tempFile.getFileName().toString();
198+
String confdDirectory = yamlConfigs[0].getParent().toString();
199199

200-
List<String> params = new ArrayList<String>();
200+
List<String> params = new ArrayList<>();
201201
params.add("--reporter");
202202
params.add("console");
203203

204-
if (confdDirectory != null) {
204+
for (Path yamlConfig : yamlConfigs) {
205205
params.add("-c");
206-
params.add(yamlFileName);
207-
params.add("--conf_directory");
208-
params.add(confdDirectory);
209-
params.add("collect");
206+
params.add(yamlConfig.getFileName().toString());
210207
}
211-
new JCommander(appConfig, params.toArray(new String[params.size()]));
208+
209+
params.add("--conf_directory");
210+
params.add(confdDirectory);
211+
params.add("collect");
212+
213+
new JCommander(appConfig, params.toArray(new String[0]));
212214
this.app = new App(appConfig);
213215
app.init(false);
214216
}
215217

218+
ConfigUtil getConfigUtil() {
219+
return new ConfigUtil(temporaryFolder.getRoot());
220+
}
216221

217222
/** Run a JMXFetch iteration. */
218223
protected void run() {
@@ -255,7 +260,7 @@ protected List<Map<String, Object>> getServiceChecks() {
255260
* @param additionalTags metric tags inherited from the bean properties
256261
* @param countTags number of metric tags
257262
* @param metricType type of the metric (gauge, histogram, ...)
258-
* @return fail if the metric was not found
263+
* @throws AssertionError if the metric was not found
259264
*/
260265
public void assertMetric(
261266
String name,

src/test/java/org/datadog/jmxfetch/TestGCMetrics.java

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -181,21 +181,29 @@ public void testDefaultNewGCMetricsIBMJ9Gencon() throws IOException {
181181
"jvm.gc.major_collection_time", "global", "counter");
182182
}
183183
}
184-
185-
private List<Map<String, Object>> startAndGetMetrics(final MisbehavingJMXServer server,
186-
final boolean newGCMetrics) throws IOException {
184+
185+
private List<Map<String, Object>> startAndGetMetrics(
186+
final MisbehavingJMXServer server,
187+
final boolean newGCMetrics
188+
) {
187189
server.start();
188190
this.initApplicationWithYamlLines(
189-
"init_config:",
190-
" is_jmx: true",
191-
" new_gc_metrics: " + newGCMetrics,
192-
"",
193-
"instances:",
194-
" - name: jmxint_container",
195-
" host: " + server.getIp(),
196-
" collect_default_jvm_metrics: true",
197-
" max_returned_metrics: 300000",
198-
" port: " + server.getRMIPort());
191+
getConfigUtil().makeTempYamlConfigFile(
192+
"config",
193+
Arrays.asList(
194+
"init_config:",
195+
" is_jmx: true",
196+
" new_gc_metrics: " + newGCMetrics,
197+
"",
198+
"instances:",
199+
" - name: jmxint_container",
200+
" host: " + server.getIp(),
201+
" collect_default_jvm_metrics: true",
202+
" max_returned_metrics: 300000",
203+
" port: " + server.getRMIPort()
204+
)
205+
)
206+
);
199207
// Run one iteration first
200208
// TODO: Investigate why we have to run this twice - AMLII-1353
201209
this.app.doIteration();

src/test/java/org/datadog/jmxfetch/TestReconnectContainer.java

Lines changed: 29 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import static org.datadog.jmxfetch.util.MetricsAssert.isDomainPresent;
88

99
import java.io.IOException;
10+
import java.nio.file.Path;
11+
import java.util.Arrays;
1012
import java.util.Collections;
1113
import java.util.List;
1214
import java.util.Map;
@@ -135,50 +137,24 @@ public void testJMXDirectReconnect() throws Exception {
135137
}
136138

137139
@Test
138-
public void testJMXFetchBasic() throws IOException, InterruptedException {
140+
public void testJMXFetchBasic() {
139141
String ipAddress = cont.getContainerInfo().getNetworkSettings().getIpAddress();
140-
this.initApplicationWithYamlLines(
141-
"init_config:",
142-
" is_jmx: true",
143-
"",
144-
"instances:",
145-
" - name: jmxint_container",
146-
" host: " + ipAddress,
147-
" collect_default_jvm_metrics: false",
148-
" max_returned_metrics: 300000",
149-
" port: " + rmiPort,
150-
" conf:",
151-
" - include:",
152-
" domain: Bohnanza"
153-
);
142+
this.initApplicationWithYamlLines(config(ipAddress, "Bohnanza"));
154143

155144
this.app.doIteration();
156145
List<Map<String, Object>> metrics = ((ConsoleReporter) this.appConfig.getReporter()).getMetrics();
157146
assertEquals(1, metrics.size());
158147
}
159148

160149
@Test
161-
public void testJMXFetchManyMetrics() throws IOException, InterruptedException {
150+
public void testJMXFetchManyMetrics() throws IOException {
162151
String ipAddress = cont.getContainerInfo().getNetworkSettings().getIpAddress();
163152
int numBeans = 100;
164153
int numAttributesPerBean = 4;
165154

166155
String testDomain = "test-domain";
167156
this.controlClient.createMBeans(testDomain, numBeans, numAttributesPerBean, 0, 0);
168-
this.initApplicationWithYamlLines(
169-
"init_config:",
170-
" is_jmx: true",
171-
"",
172-
"instances:",
173-
" - name: jmxint_container",
174-
" host: " + ipAddress,
175-
" collect_default_jvm_metrics: false",
176-
" max_returned_metrics: 300000",
177-
" port: " + rmiPort,
178-
" conf:",
179-
" - include:",
180-
" domain: " + testDomain
181-
);
157+
this.initApplicationWithYamlLines(config(ipAddress, testDomain));
182158

183159
this.app.doIteration();
184160
List<Map<String, Object>> metrics = ((ConsoleReporter) this.appConfig.getReporter()).getMetrics();
@@ -187,22 +163,9 @@ public void testJMXFetchManyMetrics() throws IOException, InterruptedException {
187163
}
188164

189165
@Test
190-
public void testJMXFetchReconnect() throws IOException, InterruptedException {
166+
public void testJMXFetchReconnect() throws IOException {
191167
String ipAddress = cont.getContainerInfo().getNetworkSettings().getIpAddress();
192-
this.initApplicationWithYamlLines(
193-
"init_config:",
194-
" is_jmx: true",
195-
"",
196-
"instances:",
197-
" - name: jmxint_container",
198-
" host: " + ipAddress,
199-
" collect_default_jvm_metrics: false",
200-
" max_returned_metrics: 300000",
201-
" port: " + rmiPort,
202-
" conf:",
203-
" - include:",
204-
" domain: Bohnanza"
205-
);
168+
this.initApplicationWithYamlLines(config(ipAddress, "Bohnanza"));
206169

207170

208171
this.app.doIteration();
@@ -232,4 +195,25 @@ public void testJMXFetchReconnect() throws IOException, InterruptedException {
232195
metrics = ((ConsoleReporter) this.appConfig.getReporter()).getMetrics();
233196
assertEquals(1, metrics.size());
234197
}
198+
199+
private Path config(String ipAddress, String domain) {
200+
return getConfigUtil().makeTempYamlConfigFile(
201+
"config",
202+
Arrays.asList(
203+
"init_config:",
204+
" is_jmx: true",
205+
"",
206+
"instances:",
207+
" - name: jmxint_container",
208+
" host: " + ipAddress,
209+
" collect_default_jvm_metrics: false",
210+
" max_returned_metrics: 300000",
211+
" port: " + rmiPort,
212+
" conf:",
213+
" - include:",
214+
" domain: " + domain
215+
)
216+
);
217+
}
218+
235219
}

0 commit comments

Comments
 (0)