1 /* 2 * Copyright (C) 2023 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 * limitations under the License. 15 */ 16 17 package com.android.server.devicelock; 18 19 import org.junit.function.ThrowingRunnable; 20 import org.junit.runners.model.TestTimedOutException; 21 22 /** 23 * Utils useful for testing 24 */ 25 final class TestUtils { TestUtils()26 private TestUtils() {} 27 28 /** 29 * Make sure that a runnable eventually finishes without throwing an exception. 30 */ eventually(ThrowingRunnable r, long timeoutMillis)31 static void eventually(ThrowingRunnable r, long timeoutMillis) { 32 long start = System.currentTimeMillis(); 33 34 while (true) { 35 try { 36 r.run(); 37 return; 38 } catch (TestTimedOutException e) { 39 throw new RuntimeException(e); 40 } catch (Throwable e) { 41 if (System.currentTimeMillis() - start < timeoutMillis) { 42 try { 43 Thread.sleep(100); 44 } catch (InterruptedException ignored) { 45 throw new RuntimeException(e); 46 } 47 } else { 48 throw new RuntimeException(e); 49 } 50 } 51 } 52 } 53 } 54