org.junit.rules.Timeout Java Examples

The following examples show how to use org.junit.rules.Timeout. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BuckBlockJUnit4ClassRunner.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #2
Source File: DelegateRunNotifier.java    From buck with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: ServiceTalkTestTimeout.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #4
Source File: ChannelTest.java    From Elastos.NET.Carrier.Android.SDK with GNU General Public License v3.0 5 votes vote down vote up
@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();
	}
}
 
Example #5
Source File: DynamicConfigIT.java    From terracotta-platform with Apache License 2.0 5 votes vote down vote up
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);
            }
          }
        }
      });
}
 
Example #6
Source File: TestTools.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static TestRule getTimeoutRule(int timeout, TimeUnit unit) {
  return IS_DEBUG ? new TestName() : Timeout.builder().withTimeout(timeout, unit).build();
}
 
Example #7
Source File: FlutterGuiTestRule.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public FlutterGuiTestRule withTimeout(long timeout, @NotNull TimeUnit timeUnits) {
  myInnerTimeout = new Timeout(timeout, timeUnits);
  myOuterTimeout = new Timeout(timeUnits.toSeconds(timeout) + 120, TimeUnit.SECONDS);
  return this;
}
 
Example #8
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
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;
                }
            }
        };
    }
}
 
Example #9
Source File: HBaseClassTestRule.java    From hbase with Apache License 2.0 4 votes vote down vote up
private HBaseClassTestRule(Class<?> clazz, Timeout timeout) {
  this.clazz = clazz;
  this.timeout = timeout;
}
 
Example #10
Source File: HBaseClassTestRule.java    From hbase with Apache License 2.0 4 votes vote down vote up
public static HBaseClassTestRule forClass(Class<?> clazz) {
  return new HBaseClassTestRule(clazz, Timeout.builder().withLookingForStuckThread(true)
      .withTimeout(getTimeoutInSeconds(clazz), TimeUnit.SECONDS).build());
}
 
Example #11
Source File: CuratorSingletonServiceTest.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Rule
public Timeout getTimeout() {
  return timeout;
}