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.sdksandbox; 18 19 import android.app.sdksandbox.SdkSandboxManager; 20 import android.app.sdksandbox.testutils.FakeSdkSandboxProcessDeathCallback; 21 import android.content.Context; 22 23 import androidx.test.platform.app.InstrumentationRegistry; 24 25 import com.android.server.sdksandbox.DeviceSupportedBaseTest; 26 27 import org.junit.Before; 28 import org.junit.runner.RunWith; 29 import org.junit.runners.JUnit4; 30 31 /** Ensure to kill sandbox before tests to avoid race conditions. */ 32 @RunWith(JUnit4.class) 33 public abstract class SandboxKillerBeforeTest extends 34 com.android.server.sdksandbox.DeviceSupportedBaseTest { 35 private SdkSandboxManager mSdkSandboxManager; 36 37 @Before killSandboxBeforeTest()38 public void killSandboxBeforeTest() throws Exception { 39 Context context = InstrumentationRegistry.getInstrumentation().getContext(); 40 mSdkSandboxManager = context.getSystemService(SdkSandboxManager.class); 41 killSandboxIfExists(); 42 } 43 44 // Returns true if the sandbox was already likely existing, false otherwise. killSandboxIfExists()45 protected boolean killSandboxIfExists() throws Exception { 46 FakeSdkSandboxProcessDeathCallback callback = new FakeSdkSandboxProcessDeathCallback(); 47 mSdkSandboxManager.addSdkSandboxProcessDeathCallback(Runnable::run, callback); 48 killSandbox(); 49 50 return callback.waitForSandboxDeath(); 51 } 52 killSandbox()53 protected void killSandbox() throws Exception { 54 // TODO(b/241542162): Avoid using reflection as a workaround once test apis can be run 55 // without issue. 56 mSdkSandboxManager.getClass().getMethod("stopSdkSandbox").invoke(mSdkSandboxManager); 57 } 58 } 59