2020import org .assertj .core .api .Assertions ;
2121import org .junit .After ;
2222import org .junit .Before ;
23+ import org .junit .Rule ;
2324import org .junit .Test ;
25+ import org .junit .rules .TestName ;
26+ import org .junit .rules .TestWatcher ;
27+ import org .junit .runner .Description ;
2428import org .slf4j .Logger ;
2529import org .slf4j .LoggerFactory ;
2630
@@ -95,13 +99,27 @@ private StreamObserver<Message> createStream(StreamObserver<Event> recv) {
9599 return in ;
96100 }
97101
102+ @ Rule
103+ public TestName currentTest = new TestName ();
104+
105+ private boolean testFailed ;
106+
107+ @ Rule
108+ public TestWatcher __ = new TestWatcher () {
109+ @ Override
110+ protected void failed (Throwable e , Description description ) {
111+ testFailed = true ;
112+ }
113+ };
114+
98115 /**
99116 * Create new unstarted context with default maxSizeBytes, collection
100117 * descriptor, and collection handle defaults.
101118 */
102119 @ Before
103120 public void startContext () throws InterruptedException {
104121 log .debug ("===================startContext==================" );
122+ log .debug (currentTest .getMethodName ());
105123
106124 assert !Thread .currentThread ().isInterrupted () : "main thread interrupted" ;
107125 assert REQUEST_QUEUE .isEmpty () : "stream contains incoming message " + REQUEST_QUEUE .peek ();
@@ -122,7 +140,11 @@ public void startContext() throws InterruptedException {
122140
123141 @ After
124142 public void reset () throws Exception {
125- if (!contextClosed ) {
143+ // Do not attempt to close the context if it has been previously closed
144+ // by the test or the test has failed. In the latter case closing the
145+ // context may lead to a deadlock if the case hasn't scheduled Results
146+ // for all submitted messages.
147+ if (!contextClosed && !testFailed ) {
126148 closeContext ();
127149 }
128150
@@ -175,6 +197,8 @@ public void test_sendOneBatch() throws Exception {
175197 // BatchContext should flush the current batch once it hits its limit.
176198 // We will ack all items in the batch and send successful result for each one.
177199 List <String > received = recvDataAndAck ();
200+ out .beforeEof (new Event .Results (received , Collections .emptyMap ()));
201+
178202 Assertions .assertThat (tasks )
179203 .extracting (TaskHandle ::id ).containsExactlyInAnyOrderElementsOf (received );
180204
@@ -183,8 +207,6 @@ public void test_sendOneBatch() throws Exception {
183207 Assertions .assertThat (CompletableFuture .allOf (tasksAcked ))
184208 .succeedsWithin (5 , TimeUnit .SECONDS );
185209
186- out .beforeEof (new Event .Results (received , Collections .emptyMap ()));
187-
188210 // Since MockServer runs in the same thread as this test,
189211 // the context will be updated before the last emitEvent returns.
190212 closeContext ();
0 commit comments