1 /*
2  * Copyright (C) 2017 The Android Open Source Project
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  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  */
15 
16 package com.android.cts.content;
17 
18 import android.util.Log;
19 
20 import org.junit.rules.TestRule;
21 import org.junit.runner.Description;
22 import org.junit.runners.model.Statement;
23 
24 /**
25  * Rule for running flaky tests that runs the test up to attempt
26  * count and if one run succeeds reports the tests as passing.
27  */
28 // TODO: Move this puppy in a common place, so ppl can use it.
29 public class FlakyTestRule implements TestRule {
30     private static final String LOG_TAG = FlakyTestRule.class.getSimpleName();
31 
32     private final int mAttemptCount;
33 
FlakyTestRule(int attemptCount)34     public FlakyTestRule(int attemptCount) {
35         mAttemptCount = attemptCount;
36     }
37 
38     @Override
apply(Statement statement, Description description)39     public Statement apply(Statement statement, Description description) {
40         return new Statement() {
41             @Override
42             public void evaluate() throws Throwable {
43                 Throwable throwable = null;
44                 for (int i = 0; i < mAttemptCount; i++) {
45                     try {
46                         statement.evaluate();
47                         return;
48                     } catch (Throwable t) {
49                         Log.e(LOG_TAG, "Test failed ", t);
50 
51                         throwable = t;
52                     }
53                 }
54                 throw throwable;
55             };
56         };
57     }
58 }
59