1 /*
2  * Copyright (C) 2021 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 android.compat.sjp.app;
18 
19 import static org.junit.Assert.assertNotNull;
20 
21 import android.content.pm.PackageManager;
22 
23 import androidx.test.platform.app.InstrumentationRegistry;
24 import androidx.test.runner.AndroidJUnit4;
25 
26 import org.junit.After;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.junit.runner.RunWith;
30 
31 import java.io.File;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.util.Set;
35 import java.util.stream.Collectors;
36 
37 /**
38  * Device-side helper app for obtaining Apex info.
39  *
40  * <p>It is not technically a test as it simply collects information, but it simplifies the usage
41  * and communication with host-side tests.
42  */
43 @RunWith(AndroidJUnit4.class)
44 public class ApexDeviceTest {
45 
46     @Before
before()47     public void before() {
48         InstrumentationRegistry.getInstrumentation().getUiAutomation()
49                 .adoptShellPermissionIdentity();
50     }
51 
52     @After
after()53     public void after() {
54         InstrumentationRegistry.getInstrumentation().getUiAutomation()
55                 .dropShellPermissionIdentity();
56     }
57 
58     /**
59      * Collects all apk-in-apex apps on the device and writes them to disk.
60      */
61     @Test
testCollectApkInApexPaths()62     public void testCollectApkInApexPaths() throws Exception {
63         Path detailsFilepath = new File("/sdcard/apk-in-apex-paths.txt").toPath();
64         final PackageManager pm = InstrumentationRegistry.getInstrumentation().getTargetContext()
65                 .getPackageManager();
66         assertNotNull("No package manager instance!", pm);
67         final Set<String> lines = pm.getInstalledPackages(0).stream()
68                 .map(pkg -> pkg.applicationInfo.sourceDir)
69                 .filter(sourceDir -> sourceDir != null && sourceDir.contains("/apex/"))
70                 .collect(Collectors.toSet());
71         Files.write(detailsFilepath, lines);
72     }
73 }
74