blob: 5ddbd96459f1a3344142ec3d5fa5fa43650e0f3b [file] [log] [blame]
Damien Martin-Guillerezf88f4d82015-09-25 13:56:55 +00001// Copyright 2014 The Bazel Authors. All rights reserved.
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +01002//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package com.google.devtools.build.lib.testutil;
16
17import static com.google.common.truth.Truth.assertWithMessage;
18
19/**
20 * Test thread implementation that allows the use of assertions within
21 * spawned threads.
22 *
23 * Main test method must call {@link TestThread#joinAndAssertState(long)}
24 * for each spawned test thread.
25 */
26public abstract class TestThread extends Thread {
27 Throwable testException = null;
28 boolean isSucceeded = false;
29
30 /**
31 * Specific test thread implementation overrides this method.
32 */
33 abstract public void runTest() throws Exception;
34
35 @Override public final void run() {
36 try {
37 runTest();
38 isSucceeded = true;
Ulf Adams795895a2015-03-06 15:58:35 +000039 } catch (Exception | AssertionError e) {
Han-Wen Nienhuysd08b27f2015-02-25 16:45:20 +010040 testException = e;
41 }
42 }
43
44 /**
45 * Joins test thread (waiting specified number of ms) and validates that
46 * it has been completed successfully.
47 */
48 public void joinAndAssertState(long timeout) throws InterruptedException {
49 join(timeout);
50 Throwable exception = this.testException;
51 if (isAlive()) {
52 exception = new AssertionError (
53 "Test thread " + getName() + " is still alive");
54 exception.setStackTrace(getStackTrace());
55 }
56 if(exception != null) {
57 AssertionError error = new AssertionError("Test thread " + getName() + " failed to execute");
58 error.initCause(exception);
59 throw error;
60 }
61 assertWithMessage("Test thread " + getName() + " has not run successfully").that(isSucceeded)
62 .isTrue();
63 }
64}