Skip to content

Commit a14af46

Browse files
authored
[fix][test] Cleanup resources if starting PulsarService fails in PulsarTestContext (apache#21467)
1 parent bb8082e commit a14af46

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

pulsar-broker/src/test/java/org/apache/pulsar/broker/testcontext/PulsarTestContext.java

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,10 @@ public static Builder builderForNonStartableContext() {
193193
* @throws Exception if there is an error closing the resources
194194
*/
195195
public void close() throws Exception {
196+
callCloseables(closeables);
197+
}
198+
199+
private static void callCloseables(List<AutoCloseable> closeables) {
196200
for (int i = closeables.size() - 1; i >= 0; i--) {
197201
try {
198202
closeables.get(i).close();
@@ -226,6 +230,7 @@ public static class Builder {
226230
protected ServiceConfiguration svcConfig = initializeConfig();
227231
protected Consumer<ServiceConfiguration> configOverrideCustomizer = this::defaultOverrideServiceConfiguration;
228232
protected Function<BrokerService, BrokerService> brokerServiceCustomizer = Function.identity();
233+
protected PulsarTestContext otherContextToClose;
229234

230235
/**
231236
* Initialize the ServiceConfiguration with default values.
@@ -401,7 +406,15 @@ public Builder reuseSpyConfig(PulsarTestContext otherContext) {
401406
* The other PulsarTestContext will be closed when this one is closed.
402407
*/
403408
public Builder chainClosing(PulsarTestContext otherContext) {
404-
registerCloseable(otherContext);
409+
otherContextToClose = otherContext;
410+
return this;
411+
}
412+
413+
/**
414+
* Registers a closeable to close as the last one by prepending it to the closeables list.
415+
*/
416+
public Builder prependCloseable(AutoCloseable closeable) {
417+
closeables.add(0, closeable);
405418
return this;
406419
}
407420

@@ -537,9 +550,14 @@ public final PulsarTestContext build() {
537550
try {
538551
super.pulsarService.start();
539552
} catch (Exception e) {
553+
callCloseables(super.closeables);
554+
super.closeables.clear();
540555
throw new RuntimeException(e);
541556
}
542557
}
558+
if (otherContextToClose != null) {
559+
prependCloseable(otherContextToClose);
560+
}
543561
brokerService(super.pulsarService.getBrokerService());
544562
return super.build();
545563
}

0 commit comments

Comments
 (0)