View Javadoc
1   /*
2    * Copyright (c) 2002-2025 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://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   */
15  package org.htmlunit.junit;
16  
17  import java.util.concurrent.atomic.AtomicInteger;
18  
19  import org.htmlunit.junit.annotation.Retry;
20  import org.junit.rules.TestRule;
21  import org.junit.runner.Description;
22  import org.junit.runners.model.Statement;
23  
24  /**
25   * Simple rule supports retry tests. We need this at least for async tests on
26   * the ci server.
27   *
28   * @author Ronald Brill
29   */
30  public class RetryRule implements TestRule {
31      private AtomicInteger retryCount_;
32  
33      /**
34       * Ctor.
35       * @param retryCount the retry count to be used
36       */
37      public RetryRule(final int retryCount) {
38          retryCount_ = new AtomicInteger(retryCount);
39      }
40  
41      @Override
42      public Statement apply(final Statement stmt, final Description desc) {
43          return statement(stmt, desc);
44      }
45  
46      private Statement statement(final Statement stmt, final Description desc) {
47          return new Statement() {
48              @Override
49              public void evaluate() throws Throwable {
50                  while (retryCount_.getAndDecrement() > 0) {
51                      try {
52                          stmt.evaluate();
53                          return;
54                      }
55                      catch (final Throwable e) {
56                          if (retryCount_.get() == 0 || desc.getAnnotation(Retry.class) == null) {
57                              throw e;
58                          }
59                      }
60                  }
61              }
62          };
63      }
64  }