1 /*
2  * Copyright (C) 2024 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.healthconnect.tests.documentprovider.utils;
18 
19 import android.database.MatrixCursor;
20 import android.os.Bundle;
21 import android.provider.DocumentsContract;
22 
23 import java.util.ArrayList;
24 
25 /** Fake document provider roots that can be configured for tests. */
26 public final class FakeDocumentProviderRoots {
27     public static FakeDocumentProviderRoots INSTANCE = new FakeDocumentProviderRoots();
28 
29     private static final String[] PROJECTION =
30             new String[] {
31                 DocumentsContract.Root.COLUMN_ROOT_ID,
32                 DocumentsContract.Root.COLUMN_TITLE,
33                 DocumentsContract.Root.COLUMN_SUMMARY,
34                 DocumentsContract.Root.COLUMN_FLAGS,
35                 DocumentsContract.Root.COLUMN_ICON,
36                 DocumentsContract.Root.COLUMN_MIME_TYPES,
37             };
38 
39     private final ArrayList<DocumentProviderRoot> mRoots = new ArrayList<>();
40     private boolean mThrowsException = false;
41 
FakeDocumentProviderRoots()42     private FakeDocumentProviderRoots() {}
43 
44     /** Returns a cursor filled with the configured roots. */
getCursor()45     public MatrixCursor getCursor() {
46         if (mThrowsException) {
47             throw new UnsupportedOperationException(
48                     "TestDocumentProviderApp is configured to throw an exception");
49         }
50 
51         final MatrixCursor cursor = new MatrixCursor(PROJECTION);
52 
53         for (DocumentProviderRoot root : mRoots) {
54             root.build(cursor.newRow());
55         }
56 
57         return cursor;
58     }
59 
60     /** Configures {@link #getCursor()} to throw an exception. */
setThrowsException()61     public void setThrowsException() {
62         mThrowsException = true;
63     }
64 
65     /** Removes all roots and resets to the default configuration. */
clear()66     public void clear() {
67         mRoots.clear();
68         mThrowsException = false;
69     }
70 
71     /** Adds the root defined in the bundle to the list of roots. */
addRoot(Bundle bundle)72     public void addRoot(Bundle bundle) {
73         DocumentProviderRoot root = new DocumentProviderRoot(bundle);
74         mRoots.add(root);
75     }
76 }
77