1 // Copyright 2023 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.net; 6 7 import static com.google.common.truth.Truth.assertThat; 8 import static com.google.common.truth.Truth.assertWithMessage; 9 10 import android.os.ConditionVariable; 11 12 import java.util.concurrent.Executor; 13 import java.util.concurrent.Executors; 14 15 /** RequestFinishedInfo.Listener for testing, which saves the RequestFinishedInfo */ 16 public class TestRequestFinishedListener extends RequestFinishedInfo.Listener { 17 private final ConditionVariable mBlock; 18 private final ConditionVariable mBlockListener = new ConditionVariable(true); 19 private RequestFinishedInfo mRequestInfo; 20 private boolean mMakeListenerThrow; 21 22 // TODO(mgersh): it's weird that you can use either this constructor or blockUntilDone() but 23 // not both. Either clean it up or document why it has to work this way. TestRequestFinishedListener(Executor executor)24 public TestRequestFinishedListener(Executor executor) { 25 super(executor); 26 mBlock = new ConditionVariable(); 27 } 28 TestRequestFinishedListener()29 public TestRequestFinishedListener() { 30 super(Executors.newSingleThreadExecutor()); 31 mBlock = new ConditionVariable(); 32 } 33 makeListenerThrow()34 public void makeListenerThrow() { 35 mMakeListenerThrow = true; 36 } 37 getRequestInfo()38 public RequestFinishedInfo getRequestInfo() { 39 return mRequestInfo; 40 } 41 blockListener()42 public void blockListener() { 43 mBlockListener.close(); 44 } 45 unblockListener()46 public void unblockListener() { 47 mBlockListener.open(); 48 } 49 50 @Override onRequestFinished(RequestFinishedInfo requestInfo)51 public void onRequestFinished(RequestFinishedInfo requestInfo) { 52 assertWithMessage("onRequestFinished called repeatedly").that(mRequestInfo).isNull(); 53 assertThat(requestInfo).isNotNull(); 54 mRequestInfo = requestInfo; 55 mBlock.open(); 56 mBlockListener.block(); 57 if (mMakeListenerThrow) { 58 throw new IllegalStateException( 59 "TestRequestFinishedListener throwing exception as requested"); 60 } 61 } 62 blockUntilDone()63 public void blockUntilDone() { 64 mBlock.block(); 65 } 66 reset()67 public void reset() { 68 mBlock.close(); 69 mRequestInfo = null; 70 } 71 } 72