Skip to content

Commit 7d75e51

Browse files
committed
[fix][test] Cleanup resources if starting PulsarService fails in PulsarTestContext (apache#21467)
(cherry picked from commit a14af46)
1 parent f0d928a commit 7d75e51

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
@@ -198,6 +198,10 @@ public static Builder builderForNonStartableContext() {
198198
* @throws Exception if there is an error closing the resources
199199
*/
200200
public void close() throws Exception {
201+
callCloseables(closeables);
202+
}
203+
204+
private static void callCloseables(List<AutoCloseable> closeables) {
201205
for (int i = closeables.size() - 1; i >= 0; i--) {
202206
try {
203207
closeables.get(i).close();
@@ -246,6 +250,7 @@ public static class Builder {
246250
protected boolean configOverrideCalled = false;
247251
protected Function<BrokerService, BrokerService> brokerServiceCustomizer = Function.identity();
248252
protected WithMockZooKeeperOrTestZKServer withMockZooKeeperOrTestZKServer;
253+
protected PulsarTestContext otherContextToClose;
249254

250255
/**
251256
* Initialize the ServiceConfiguration with default values.
@@ -429,7 +434,15 @@ public Builder reuseSpyConfig(PulsarTestContext otherContext) {
429434
* The other PulsarTestContext will be closed when this one is closed.
430435
*/
431436
public Builder chainClosing(PulsarTestContext otherContext) {
432-
registerCloseable(otherContext);
437+
otherContextToClose = otherContext;
438+
return this;
439+
}
440+
441+
/**
442+
* Registers a closeable to close as the last one by prepending it to the closeables list.
443+
*/
444+
public Builder prependCloseable(AutoCloseable closeable) {
445+
closeables.add(0, closeable);
433446
return this;
434447
}
435448

@@ -584,9 +597,14 @@ public final PulsarTestContext build() {
584597
try {
585598
super.pulsarService.start();
586599
} catch (Exception e) {
600+
callCloseables(super.closeables);
601+
super.closeables.clear();
587602
throw new RuntimeException(e);
588603
}
589604
}
605+
if (otherContextToClose != null) {
606+
prependCloseable(otherContextToClose);
607+
}
590608
brokerService(super.pulsarService.getBrokerService());
591609
return super.build();
592610
}

0 commit comments

Comments
 (0)