aboutsummaryrefslogtreecommitdiff
path: root/tests/src/com/android/tradefed/device/contentprovider/ContentProviderHandlerTest.java
blob: e72b23a21927c01ccce6fea2e79b373b7a2c698d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.tradefed.device.contentprovider;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;

import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.util.CommandResult;
import com.android.tradefed.util.CommandStatus;
import com.android.tradefed.util.FileUtil;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;

import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/** Run unit tests for {@link ContentProviderHandler}. */
@RunWith(JUnit4.class)
public class ContentProviderHandlerTest {

    private ContentProviderHandler mProvider;
    private ITestDevice mMockDevice;

    @Before
    public void setUp() {
        mMockDevice = Mockito.mock(ITestDevice.class);
        mProvider = new ContentProviderHandler(mMockDevice);
    }

    @After
    public void tearDown() throws Exception {
        mProvider.tearDown();
    }

    /** Test the install flow. */
    @Test
    public void testSetUp_install() throws Exception {
        Set<String> set = new HashSet<>();
        doReturn(set).when(mMockDevice).getInstalledPackageNames();
        doReturn(1).when(mMockDevice).getCurrentUser();
        doReturn(null).when(mMockDevice).installPackage(any(), eq(true), eq(true));
        assertTrue(mProvider.setUp());
    }

    @Test
    public void testSetUp_alreadyInstalled() throws Exception {
        Set<String> set = new HashSet<>();
        set.add(ContentProviderHandler.PACKAGE_NAME);
        doReturn(set).when(mMockDevice).getInstalledPackageNames();

        assertTrue(mProvider.setUp());
    }

    @Test
    public void testSetUp_installFail() throws Exception {
        Set<String> set = new HashSet<>();
        doReturn(set).when(mMockDevice).getInstalledPackageNames();
        doReturn(1).when(mMockDevice).getCurrentUser();
        doReturn("fail").when(mMockDevice).installPackage(any(), eq(true), eq(true));

        assertFalse(mProvider.setUp());
    }

    /** Test {@link ContentProviderHandler#deleteFile(String)}. */
    @Test
    public void testDeleteFile() throws Exception {
        String devicePath = "path/somewhere/file.txt";
        doReturn(99).when(mMockDevice).getCurrentUser();
        doReturn(mockSuccess())
                .when(mMockDevice)
                .executeShellV2Command(
                        eq(
                                "content delete --user 99 --uri "
                                        + ContentProviderHandler.createEscapedContentUri(
                                                devicePath)));
        assertTrue(mProvider.deleteFile(devicePath));
    }

    /** Test {@link ContentProviderHandler#deleteFile(String)}. */
    @Test
    public void testDeleteFile_fail() throws Exception {
        String devicePath = "path/somewhere/file.txt";
        CommandResult result = new CommandResult(CommandStatus.FAILED);
        result.setStdout("");
        result.setStderr("couldn't find the file");
        doReturn(99).when(mMockDevice).getCurrentUser();
        doReturn(result)
                .when(mMockDevice)
                .executeShellV2Command(
                        eq(
                                "content delete --user 99 --uri "
                                        + ContentProviderHandler.createEscapedContentUri(
                                                devicePath)));
        assertFalse(mProvider.deleteFile(devicePath));
    }

    /** Test {@link ContentProviderHandler#deleteFile(String)}. */
    @Test
    public void testError() throws Exception {
        String devicePath = "path/somewhere/file.txt";
        CommandResult result = new CommandResult(CommandStatus.SUCCESS);
        result.setStdout("[ERROR] Unsupported operation: delete");
        doReturn(99).when(mMockDevice).getCurrentUser();
        doReturn(result)
                .when(mMockDevice)
                .executeShellV2Command(
                        eq(
                                "content delete --user 99 --uri "
                                        + ContentProviderHandler.createEscapedContentUri(
                                                devicePath)));
        assertFalse(mProvider.deleteFile(devicePath));
    }

    /** Test {@link ContentProviderHandler#pushFile(File, String)}. */
    @Test
    public void testPushFile() throws Exception {
        File toPush = FileUtil.createTempFile("content-provider-test", ".txt");
        try {
            String devicePath = "path/somewhere/file.txt";
            doReturn(99).when(mMockDevice).getCurrentUser();
            doReturn(mockSuccess())
                    .when(mMockDevice)
                    .executeShellV2Command(
                            eq(
                                    "content write --user 99 --uri "
                                            + ContentProviderHandler.createEscapedContentUri(
                                                    devicePath)),
                            eq(toPush));
            assertTrue(mProvider.pushFile(toPush, devicePath));
        } finally {
            FileUtil.deleteFile(toPush);
        }
    }

    /** Test {@link ContentProviderHandler#pullFile(String, File)}. */
    @Test
    public void testPullFile_verifyShellCommand() throws Exception {
        File pullTo = FileUtil.createTempFile("content-provider-test", ".txt");
        String devicePath = "path/somewhere/file.txt";
        doReturn(99).when(mMockDevice).getCurrentUser();
        mockPullFileSuccess();

        try {
            mProvider.pullFile(devicePath, pullTo);

            // Capture the shell command used by pullFile.
            ArgumentCaptor<String> shellCommandCaptor = ArgumentCaptor.forClass(String.class);
            verify(mMockDevice)
                    .executeShellV2Command(shellCommandCaptor.capture(), any(OutputStream.class));

            // Verify the command.
            assertEquals(
                    shellCommandCaptor.getValue(),
                    "content read --user 99 --uri "
                            + ContentProviderHandler.createEscapedContentUri(devicePath));
        } finally {
            FileUtil.deleteFile(pullTo);
        }
    }

    /** Test {@link ContentProviderHandler#pullFile(String, File)}. */
    @Test
    public void testPullFile_createLocalFileIfNotExist() throws Exception {
        File pullTo = FileUtil.createTempFile("content-provider-test", ".txt");
        // Delete to test unexisting file.
        pullTo.delete();
        String devicePath = "path/somewhere/file.txt";
        mockPullFileSuccess();

        try {
            assertFalse(pullTo.exists());
            assertTrue(mProvider.pullFile(devicePath, pullTo));
            assertTrue(pullTo.exists());
        } finally {
            FileUtil.deleteFile(pullTo);
        }
    }

    /** Test {@link ContentProviderHandler#pullDir(String, File)}. */
    @Test
    public void testPullDir_EmptyDirectory() throws Exception {
        File pullTo = FileUtil.createTempDir("content-provider-test");

        doReturn("No result found.\n").when(mMockDevice).executeShellCommand(anyString());

        try {
            assertTrue(mProvider.pullDir("path/somewhere", pullTo));
        } finally {
            FileUtil.recursiveDelete(pullTo);
        }
    }

    /**
     * Test {@link ContentProviderHandler#pullDir(String, File)} to pull a directory that contains
     * one text file.
     */
    @Test
    public void testPullDir_OneFile() throws Exception {
        File pullTo = FileUtil.createTempDir("content-provider-test");

        String devicePath = "path/somewhere";
        String fileName = "content-provider-file.txt";

        doReturn(createMockFileRow(fileName, devicePath + "/" + fileName, "text/plain"))
                .when(mMockDevice)
                .executeShellCommand(anyString());
        mockPullFileSuccess();

        try {
            // Assert that local directory is empty.
            assertEquals(pullTo.listFiles().length, 0);
            mProvider.pullDir(devicePath, pullTo);

            // Assert that a file has been pulled inside the directory.
            assertEquals(pullTo.listFiles().length, 1);
            assertEquals(pullTo.listFiles()[0].getName(), fileName);
        } finally {
            FileUtil.recursiveDelete(pullTo);
        }
    }

    /**
     * Test {@link ContentProviderHandler#pullDir(String, File)} to pull a directory that contains
     * another directory.
     */
    @Test
    public void testPullDir_RecursiveSubDir() throws Exception {
        File pullTo = FileUtil.createTempDir("content-provider-test");

        String devicePath = "path/somewhere";
        String subDirName = "test-subdir";
        String subDirPath = devicePath + "/" + subDirName;
        String fileName = "test-file.txt";

        doReturn(99).when(mMockDevice).getCurrentUser();
        // Mock the result for the directory.
        doReturn(createMockDirRow(subDirName, subDirPath))
                .when(mMockDevice)
                .executeShellCommand(
                        "content query --user 99 --uri "
                                + ContentProviderHandler.createEscapedContentUri(devicePath));

        // Mock the result for the subdir.
        doReturn(createMockFileRow(fileName, subDirPath + "/" + fileName, "text/plain"))
                .when(mMockDevice)
                .executeShellCommand(
                        "content query --user 99 --uri "
                                + ContentProviderHandler.createEscapedContentUri(
                                        devicePath + "/" + subDirName));

        mockPullFileSuccess();

        try {
            // Assert that local directory is empty.
            assertEquals(pullTo.listFiles().length, 0);
            mProvider.pullDir(devicePath, pullTo);

            // Assert that a subdirectory has been created.
            assertEquals(pullTo.listFiles().length, 1);
            assertEquals(pullTo.listFiles()[0].getName(), subDirName);
            assertTrue(pullTo.listFiles()[0].isDirectory());

            // Assert that a file has been pulled inside the subdirectory.
            assertEquals(pullTo.listFiles()[0].listFiles().length, 1);
            assertEquals(pullTo.listFiles()[0].listFiles()[0].getName(), fileName);
        } finally {
            FileUtil.recursiveDelete(pullTo);
        }
    }

    @Test
    public void testCreateUri() {
        String espacedUrl =
                ContentProviderHandler.createEscapedContentUri("filepath/file name spaced (data)");
        // We expect the full url to be quoted to avoid space issues and the URL to be encoded.
        assertEquals(
                "\"content://android.tradefed.contentprovider/filepath%252Ffile%2520name"
                        + "%2520spaced%2520%28data%29\"",
                espacedUrl);
    }

    @Test
    public void testParseQueryResultRow() {
        String row =
                "Row: 1 name=name spaced with , ,comma, "
                        + "absolute_path=/storage/emulated/0/Alarms/name spaced with , ,comma, "
                        + "is_directory=true, mime_type=NULL, metadata=NULL";

        HashMap<String, String> columnValues = mProvider.parseQueryResultRow(row);

        assertEquals(
                columnValues.get(ContentProviderHandler.COLUMN_NAME), "name spaced with , ,comma");
        assertEquals(
                columnValues.get(ContentProviderHandler.COLUMN_ABSOLUTE_PATH),
                "/storage/emulated/0/Alarms/name spaced with , ,comma");
        assertEquals(columnValues.get(ContentProviderHandler.COLUMN_DIRECTORY), "true");
        assertEquals(columnValues.get(ContentProviderHandler.COLUMN_MIME_TYPE), "NULL");
        assertEquals(columnValues.get(ContentProviderHandler.COLUMN_METADATA), "NULL");
    }

    private CommandResult mockSuccess() {
        CommandResult result = new CommandResult(CommandStatus.SUCCESS);
        result.setStderr("");
        result.setStdout("");
        return result;
    }

    private void mockPullFileSuccess() throws Exception {
        doReturn(mockSuccess())
                .when(mMockDevice)
                .executeShellV2Command(anyString(), any(OutputStream.class));
    }

    private String createMockDirRow(String name, String path) {
        return String.format(
                "Row: 1 name=%s, absolute_path=%s, is_directory=%b, mime_type=NULL, metadata=NULL",
                name, path, true);
    }

    private String createMockFileRow(String name, String path, String mimeType) {
        return String.format(
                "Row: 1 name=%s, absolute_path=%s, is_directory=%b, mime_type=%s, metadata=NULL",
                name, path, false, mimeType);
    }
}