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.appsearch.app.a;
18 
19 import static com.android.server.appsearch.testing.AppSearchTestUtils.checkIsBatchResultSuccess;
20 import static com.android.server.appsearch.testing.AppSearchTestUtils.doGet;
21 
22 import static com.google.common.truth.Truth.assertThat;
23 
24 import static org.testng.Assert.expectThrows;
25 
26 import android.app.UiAutomation;
27 import android.app.appsearch.AppSearchBatchResult;
28 import android.app.appsearch.AppSearchManager;
29 import android.app.appsearch.AppSearchResult;
30 import android.app.appsearch.AppSearchSchema;
31 import android.app.appsearch.AppSearchSessionShim;
32 import android.app.appsearch.GenericDocument;
33 import android.app.appsearch.GetByDocumentIdRequest;
34 import android.app.appsearch.PackageIdentifier;
35 import android.app.appsearch.PutDocumentsRequest;
36 import android.app.appsearch.SetSchemaRequest;
37 import android.os.Bundle;
38 
39 import androidx.test.ext.junit.runners.AndroidJUnit4;
40 import androidx.test.platform.app.InstrumentationRegistry;
41 
42 import com.android.server.appsearch.testing.AppSearchSessionShimImpl;
43 
44 import com.google.common.io.BaseEncoding;
45 
46 import org.junit.Before;
47 import org.junit.Test;
48 import org.junit.runner.RunWith;
49 
50 import java.util.List;
51 import java.util.concurrent.ExecutionException;
52 
53 @RunWith(AndroidJUnit4.class)
54 public class AppSearchDeviceTest {
55 
56     private static final String DB_NAME = "";
57     private static final String NAMESPACE = "namespace";
58     private static final String ID = "id";
59     private static final String USER_ID_KEY = "userId";
60     private static final AppSearchSchema SCHEMA = new AppSearchSchema.Builder("testSchema")
61             .addProperty(new AppSearchSchema.StringPropertyConfig.Builder("subject")
62                     .setCardinality(AppSearchSchema.PropertyConfig.CARDINALITY_OPTIONAL)
63                     .setIndexingType(
64                             AppSearchSchema.StringPropertyConfig.INDEXING_TYPE_PREFIXES)
65                     .setTokenizerType(AppSearchSchema.StringPropertyConfig.TOKENIZER_TYPE_PLAIN)
66                     .build())
67             .build();
68     private static final GenericDocument DOCUMENT =
69             new GenericDocument.Builder<>(NAMESPACE, ID, SCHEMA.getSchemaType())
70                     .setPropertyString("subject", "testPut example1")
71                     .setCreationTimestampMillis(12345L)
72                     .build();
73 
74     private static final String PKG_B = "android.appsearch.app.b";
75 
76     // To generate, run `apksigner` on the build APK. e.g.
77     //   ./apksigner verify --print-certs \
78     //   ~/sc-dev/out/soong/.intermediates/cts/tests/appsearch/CtsAppSearchTestHelperA/\
79     //   android_common/CtsAppSearchTestHelperA.apk`
80     // to get the SHA-256 digest. All characters need to be uppercase.
81     //
82     // Note: May need to switch the "sdk_version" of the test app from "test_current" to "30" before
83     // building the apk and running apksigner
84     private static final byte[] PKG_B_CERT_SHA256 = BaseEncoding.base16().decode(
85             "3D7A1AAE7AE8B9949BE93E071F3702AA38695B0F99B5FC4B2E8B364AC78FFDB2");
86 
87     private AppSearchSessionShim mDb;
88     private UiAutomation mUiAutomation;
89 
90     @Before
setUp()91     public void setUp() throws Exception {
92         mDb = AppSearchSessionShimImpl.createSearchSession(
93                 new AppSearchManager.SearchContext.Builder(DB_NAME).build()).get();
94         mUiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
95     }
96 
97     @Test
testPutDocuments()98     public void testPutDocuments() throws Exception {
99         // Schema registration
100         mDb.setSchema(new SetSchemaRequest.Builder().addSchemas(SCHEMA)
101                 .setSchemaTypeVisibilityForPackage(SCHEMA.getSchemaType(), /*visible=*/ true,
102                         new PackageIdentifier(PKG_B, PKG_B_CERT_SHA256)).build()).get();
103 
104         // Index a document
105         AppSearchBatchResult<String, Void> result = checkIsBatchResultSuccess(
106                 mDb.put(new PutDocumentsRequest.Builder().addGenericDocuments(DOCUMENT).build()));
107         assertThat(result.getSuccesses()).containsExactly(ID, /*v0=*/null);
108         assertThat(result.getFailures()).isEmpty();
109     }
110 
111     @Test
testGetDocuments_exist()112     public void testGetDocuments_exist() throws Exception {
113         List<GenericDocument> outDocuments = doGet(mDb, NAMESPACE, ID);
114         assertThat(outDocuments).containsExactly(DOCUMENT);
115     }
116 
117     @Test
closeAndFlush()118     public void closeAndFlush() {
119         mDb.close();
120     }
121 
122     @Test
testGetDocuments_nonexist()123     public void testGetDocuments_nonexist() throws Exception {
124         AppSearchBatchResult<String, GenericDocument> getResult = mDb.getByDocumentId(
125                 new GetByDocumentIdRequest.Builder(NAMESPACE).addIds(ID).build()).get();
126         assertThat(getResult.getFailures().get(ID).getResultCode())
127                 .isEqualTo(AppSearchResult.RESULT_NOT_FOUND);
128     }
129 
130     /**
131      * Clear generated data during the test.
132      *
133      * <p>Device side tests will be a part of host side test. We should clear the test data in the
134      * host side tearDown only. Otherwise, it will wipe the data in the middle of a host side test.
135      */
136     @Test
clearTestData()137     public void clearTestData() throws Exception {
138         mDb.setSchema(new SetSchemaRequest.Builder().setForceOverride(true).build()).get();
139     }
140 }
141