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