下面列出了怎么用org.junit.rules.Timeout的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @return {@code true} if the test class has any fields annotated with {@code Rule} whose type is
* {@link Timeout}.
*/
static boolean hasTimeoutRule(TestClass testClass) {
// Many protected convenience methods in BlockJUnit4ClassRunner that are available in JUnit 4.11
// such as getTestRules(Object) were not public until
// https://github.com/junit-team/junit/commit/8782efa08abf5d47afdc16740678661443706740,
// which appears to be JUnit 4.9. Because we allow users to use JUnit 4.7, we need to include a
// custom implementation that is backwards compatible to JUnit 4.7.
List<FrameworkField> fields = testClass.getAnnotatedFields(Rule.class);
for (FrameworkField field : fields) {
if (field.getField().getType().equals(Timeout.class)) {
return true;
}
}
return false;
}
boolean hasJunitTimeout(Description description) {
// Do not do apply the default timeout if the test has its own @Test(timeout).
Test testAnnotation = description.getAnnotation(Test.class);
if (testAnnotation != null && testAnnotation.timeout() > 0) {
return true;
}
// Do not do apply the default timeout if the test has its own @Rule Timeout.
if (runner instanceof ParentRunner) {
return BuckBlockJUnit4ClassRunner.hasTimeoutRule(((ParentRunner) runner).getTestClass());
}
Class<?> clazz = description.getTestClass();
while (clazz != null) {
for (Field field : clazz.getFields()) {
if (field.getAnnotationsByType(Rule.class).length > 0
&& field.getType().equals(Timeout.class)) {
return true;
}
}
clazz = clazz.getSuperclass();
}
return false;
}
@Override
public Statement apply(Statement base, Description description) {
// Check if multiple Timeout are present and annotated with @Rule.
Class<?> clazz = description.getTestClass();
List<Class<?>> timeoutRuleClasses = new ArrayList<>(2);
do {
for (Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(Rule.class) && Timeout.class.isAssignableFrom(field.getType())) {
timeoutRuleClasses.add(clazz);
}
}
} while ((clazz = clazz.getSuperclass()) != Object.class);
if (timeoutRuleClasses.size() > 1) {
StringBuilder sb = new StringBuilder(256)
.append("Only one @Rule for a Timeout is allowed, but ")
.append(timeoutRuleClasses.size())
.append(" were detected in types: ");
for (Class<?> clazz2 : timeoutRuleClasses) {
sb.append(clazz2.getName()).append(", ");
}
sb.setLength(sb.length() - 2);
throw new IllegalStateException(sb.toString());
}
// If timeout is specified in @Test, let that have precedence over the global timeout.
Test testAnnotation = description.getAnnotation(Test.class);
if (testAnnotation != null) {
long timeout = testAnnotation.timeout();
if (timeout > 0) {
return new TimeoutStatement(base, timeout, TimeUnit.MILLISECONDS, onTimeout);
}
}
return new TimeoutStatement(base, getTimeout(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS, onTimeout);
}
@Override
public void onChannelClose(Stream stream, int channel, CloseReason reason) {
Log.d(TAG, String.format("Channel %d closeing with %s.", channel, reason.toString()));
LocalData data = (LocalData)context.getExtra().getExtraData();
if (reason == CloseReason.Error || reason == CloseReason.Timeout) {
data.mChannelErrorStates[channel - 1] = 1;
}
synchronized (this) {
this.notify();
}
}
public DynamicConfigIT(Duration testTimeout, Path parentTmpDir) {
ClusterDefinition clusterDef = getClass().getAnnotation(ClusterDefinition.class);
this.timeout = testTimeout.toMillis();
this.rules = RuleChain.emptyRuleChain()
.around(tmpDir = new TmpDir(parentTmpDir, false))
.around(angela = new AngelaRule(createConfigurationContext(clusterDef.stripes(), clusterDef.nodesPerStripe()), clusterDef.autoStart(), clusterDef.autoActivate()) {
@Override
public void startNode(int stripeId, int nodeId) {
// let the subclasses control the node startup
DynamicConfigIT.this.startNode(stripeId, nodeId);
}
})
.around(Timeout.millis(testTimeout.toMillis()))
.around(new ExtendedTestRule() {
@Override
protected void before(Description description) throws Throwable {
// upload tc logging config, but ONLY IF EXISTS !
URL tcLoggingConfig = this.getClass().getResource("/tc-logback.xml");
if (tcLoggingConfig != null) {
List<TerracottaServer> servers = angela.tsa().getTsaConfigurationContext().getTopology().getServers();
for (TerracottaServer s : servers) {
try {
RemoteFolder folder = angela.tsa().browse(s, "");
folder.upload("logback-test.xml", tcLoggingConfig);
} catch (IOException exp) {
LOGGER.warn("unable to upload logback configuration", exp);
}
}
}
// wait for server startup if auto-activated
if (clusterDef.autoStart() && clusterDef.autoActivate()) {
for (int stripeId = 1; stripeId <= clusterDef.stripes(); stripeId++) {
waitForActive(stripeId);
waitForPassives(stripeId);
}
}
}
});
}
public static TestRule getTimeoutRule(int timeout, TimeUnit unit) {
return IS_DEBUG ? new TestName() : Timeout.builder().withTimeout(timeout, unit).build();
}
public FlutterGuiTestRule withTimeout(long timeout, @NotNull TimeUnit timeUnits) {
myInnerTimeout = new Timeout(timeout, timeUnits);
myOuterTimeout = new Timeout(timeUnits.toSeconds(timeout) + 120, TimeUnit.SECONDS);
return this;
}
public Statement apply(final Statement base, final Description description) {
if (description.getAnnotation(WithoutJenkins.class) != null) {
// request has been made to not create the instance for this test method
return base;
}
Statement wrapped = new Statement() {
@Override
public void evaluate() throws Throwable {
testDescription = description;
Thread t = Thread.currentThread();
String o = t.getName();
t.setName("Executing "+ testDescription.getDisplayName());
System.out.println("=== Starting " + testDescription.getDisplayName());
before();
try {
// so that test code has all the access to the system
ACL.impersonate(ACL.SYSTEM);
try {
base.evaluate();
} catch (Throwable th) {
// allow the late attachment of a debugger in case of a failure. Useful
// for diagnosing a rare failure
try {
throw new BreakException();
} catch (BreakException e) {}
RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class);
if (rf != null) {
System.err.println("Note: known to randomly fail: " + rf.value());
}
throw th;
}
} finally {
after();
testDescription = null;
t.setName(o);
}
}
};
final int testTimeout = getTestTimeoutOverride(description);
if (testTimeout <= 0) {
System.out.println("Test timeout disabled.");
return wrapped;
} else {
final Statement timeoutStatement = Timeout.seconds(testTimeout).apply(wrapped, description);
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
timeoutStatement.evaluate();
} catch (TestTimedOutException x) {
// withLookingForStuckThread does not work well; better to just have a full thread dump.
LOGGER.warning(String.format("Test timed out (after %d seconds).", testTimeout));
dumpThreads();
throw x;
}
}
};
}
}
private HBaseClassTestRule(Class<?> clazz, Timeout timeout) {
this.clazz = clazz;
this.timeout = timeout;
}
public static HBaseClassTestRule forClass(Class<?> clazz) {
return new HBaseClassTestRule(clazz, Timeout.builder().withLookingForStuckThread(true)
.withTimeout(getTimeoutInSeconds(clazz), TimeUnit.SECONDS).build());
}
@Rule
public Timeout getTimeout() {
return timeout;
}