|
| 1 | +package org.eclipse.ui.editors.tests; |
| 2 | + |
| 3 | +import java.util.concurrent.TimeUnit; |
| 4 | + |
| 5 | +import org.junit.Assert; |
| 6 | +import org.junit.rules.ExternalResource; |
| 7 | + |
| 8 | +import org.eclipse.swt.widgets.Display; |
| 9 | + |
| 10 | +import org.eclipse.core.runtime.jobs.Job; |
| 11 | + |
| 12 | +/** |
| 13 | + * JUnit 4 rule to clean up state that can otherwise leak through SWT between |
| 14 | + * tests. |
| 15 | + */ |
| 16 | +public class TestUtilCleanupRule extends ExternalResource { |
| 17 | + @Override |
| 18 | + protected void after() { |
| 19 | + // Ensure that the Thread.interrupted() flag didn't leak. |
| 20 | + Assert.assertFalse("The main thread should not be interrupted at the end of a test", Thread.interrupted()); |
| 21 | + // Wait for any outstanding jobs to finish. Protect against deadlock by terminating the wait after a timeout. |
| 22 | + boolean timedOut = waitForJobs(0, TimeUnit.MINUTES.toMillis(3)); |
| 23 | + Assert.assertFalse("Some Job did not terminate at the end of the test", timedOut); |
| 24 | + // Wait for any pending *syncExec calls to finish |
| 25 | + runEventLoop(); |
| 26 | + // Ensure that the Thread.interrupted() flag didn't leak. |
| 27 | + Assert.assertFalse("The main thread should not be interrupted at the end of a test", Thread.interrupted()); |
| 28 | + } |
| 29 | + |
| 30 | + private static void runEventLoop() { |
| 31 | + Display display = Display.getCurrent(); |
| 32 | + if (display != null && !display.isDisposed()) { |
| 33 | + while (display.readAndDispatch()) { |
| 34 | + // Keep pumping events until the queue is empty |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + private static boolean waitForJobs(long minTimeMs, long maxTimeMs) { |
| 40 | + if (maxTimeMs < minTimeMs) { |
| 41 | + throw new IllegalArgumentException("Max time is smaller as min time!"); |
| 42 | + } |
| 43 | + final long start = System.currentTimeMillis(); |
| 44 | + while (System.currentTimeMillis() - start < minTimeMs) { |
| 45 | + runEventLoop(); |
| 46 | + try { |
| 47 | + Thread.sleep(100); |
| 48 | + } catch (InterruptedException e) { |
| 49 | + // Uninterruptable |
| 50 | + } |
| 51 | + } |
| 52 | + while (!Job.getJobManager().isIdle()) { |
| 53 | + if (System.currentTimeMillis() - start >= maxTimeMs) { |
| 54 | + return true; |
| 55 | + } |
| 56 | + runEventLoop(); |
| 57 | + try { |
| 58 | + Thread.sleep(100); |
| 59 | + } catch (InterruptedException e) { |
| 60 | + // Uninterruptable |
| 61 | + } |
| 62 | + } |
| 63 | + return false; |
| 64 | + } |
| 65 | +} |
0 commit comments