From 32b62d3e30aa43ed6a9f9cfd8fa8cc71002acf20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20K=C3=BCrten?= Date: Fri, 4 Mar 2022 07:57:50 +0100 Subject: [PATCH] Allow BrambleTestCase to handle background thread exceptions gracefully during after() --- .../bramble/test/BrambleTestCase.java | 16 +++++++++++----- .../bramble/test/ThreadExceptionTest.java | 5 ++++- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/bramble-api/src/test/java/org/briarproject/bramble/test/BrambleTestCase.java b/bramble-api/src/test/java/org/briarproject/bramble/test/BrambleTestCase.java index 279c35d70..c2d90f37e 100644 --- a/bramble-api/src/test/java/org/briarproject/bramble/test/BrambleTestCase.java +++ b/bramble-api/src/test/java/org/briarproject/bramble/test/BrambleTestCase.java @@ -4,31 +4,37 @@ import org.junit.After; import org.junit.Before; import java.lang.Thread.UncaughtExceptionHandler; +import java.util.logging.Level; +import java.util.logging.Logger; +import static java.util.logging.Logger.getLogger; import static org.junit.Assert.fail; public abstract class BrambleTestCase { - private volatile boolean exceptionInBackgroundThread = false; + private static final Logger LOG = + getLogger(BrambleTestCase.class.getName()); + + protected volatile boolean exceptionInBackgroundThread = false; public BrambleTestCase() { // Ensure exceptions thrown on worker threads cause tests to fail UncaughtExceptionHandler fail = (thread, throwable) -> { - throwable.printStackTrace(); + LOG.log(Level.WARNING, "Caught unhandled exception", throwable); exceptionInBackgroundThread = true; }; Thread.setDefaultUncaughtExceptionHandler(fail); } @Before - public void before() { + public void beforeBrambleTestCase() { exceptionInBackgroundThread = false; } @After - public void after() { + public void afterBrambleTestCase() { if (exceptionInBackgroundThread) { - fail("background thread has thrown an exception"); + fail("background thread has thrown an exception unexpectedly"); } } } diff --git a/bramble-api/src/test/java/org/briarproject/bramble/test/ThreadExceptionTest.java b/bramble-api/src/test/java/org/briarproject/bramble/test/ThreadExceptionTest.java index 184c057d8..464f9df0d 100644 --- a/bramble-api/src/test/java/org/briarproject/bramble/test/ThreadExceptionTest.java +++ b/bramble-api/src/test/java/org/briarproject/bramble/test/ThreadExceptionTest.java @@ -1,5 +1,6 @@ package org.briarproject.bramble.test; +import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.fail; @@ -27,7 +28,9 @@ public class ThreadExceptionTest extends BrambleTestCase { System.out.println("interrupted while joining thread"); fail(); } + + Assert.assertTrue(exceptionInBackgroundThread); + exceptionInBackgroundThread = false; } - }