1 /* 2 * Copyright (C) 2022 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.safetycenter.testing 18 19 import android.os.Build.VERSION_CODES.TIRAMISU 20 import android.safetycenter.SafetyCenterData 21 import android.safetycenter.SafetyCenterErrorDetails 22 import android.safetycenter.SafetyCenterManager.OnSafetyCenterDataChangedListener 23 import androidx.annotation.RequiresApi 24 import com.android.safetycenter.testing.Coroutines.TIMEOUT_LONG 25 import com.android.safetycenter.testing.Coroutines.runBlockingWithTimeout 26 import java.time.Duration 27 import kotlinx.coroutines.channels.Channel 28 29 /** 30 * An [OnSafetyCenterDataChangedListener] that facilitates receiving updates from SafetyCenter in 31 * tests. 32 */ 33 @RequiresApi(TIRAMISU) 34 class SafetyCenterTestListener : OnSafetyCenterDataChangedListener { 35 private val dataChannel = Channel<SafetyCenterData>(Channel.UNLIMITED) 36 private val errorChannel = Channel<SafetyCenterErrorDetails>(Channel.UNLIMITED) 37 onSafetyCenterDataChangednull38 override fun onSafetyCenterDataChanged(data: SafetyCenterData) { 39 runBlockingWithTimeout { dataChannel.send(data) } 40 } 41 onErrornull42 override fun onError(errorDetails: SafetyCenterErrorDetails) { 43 // This call to super is needed for code coverage purposes, see b/272351657 for more 44 // details. The default impl of the interface is a no-op so the call to super is a no-op. 45 super.onError(errorDetails) 46 runBlockingWithTimeout { errorChannel.send(errorDetails) } 47 } 48 49 /** Waits for a [SafetyCenterData] update from SafetyCenter within the given [timeout]. */ receiveSafetyCenterDatanull50 fun receiveSafetyCenterData(timeout: Duration = TIMEOUT_LONG) = 51 runBlockingWithTimeout(timeout) { dataChannel.receive() } 52 53 /** 54 * Waits for a [SafetyCenterErrorDetails] update from SafetyCenter within the given [timeout]. 55 */ receiveSafetyCenterErrorDetailsnull56 fun receiveSafetyCenterErrorDetails(timeout: Duration = TIMEOUT_LONG) = 57 runBlockingWithTimeout(timeout) { errorChannel.receive() } 58 59 /** Cancels any pending update on this [SafetyCenterTestListener]. */ cancelnull60 fun cancel() { 61 dataChannel.cancel() 62 errorChannel.cancel() 63 } 64 } 65