1 /*
2  * Copyright (C) 2019 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.wallpaperbackup;
18 
19 import static android.app.WallpaperManager.FLAG_LOCK;
20 import static android.app.WallpaperManager.FLAG_SYSTEM;
21 import static android.os.ParcelFileDescriptor.MODE_READ_ONLY;
22 
23 import static com.android.wallpaperbackup.WallpaperBackupAgent.LOCK_WALLPAPER_STAGE;
24 import static com.android.wallpaperbackup.WallpaperBackupAgent.SYSTEM_WALLPAPER_STAGE;
25 import static com.android.wallpaperbackup.WallpaperBackupAgent.WALLPAPER_INFO_STAGE;
26 import static com.android.wallpaperbackup.WallpaperEventLogger.ERROR_INELIGIBLE;
27 import static com.android.wallpaperbackup.WallpaperEventLogger.ERROR_NO_METADATA;
28 import static com.android.wallpaperbackup.WallpaperEventLogger.ERROR_NO_WALLPAPER;
29 import static com.android.wallpaperbackup.WallpaperEventLogger.ERROR_QUOTA_EXCEEDED;
30 import static com.android.wallpaperbackup.WallpaperEventLogger.WALLPAPER_IMG_LOCK;
31 import static com.android.wallpaperbackup.WallpaperEventLogger.WALLPAPER_IMG_SYSTEM;
32 import static com.android.wallpaperbackup.WallpaperEventLogger.WALLPAPER_LIVE_LOCK;
33 import static com.android.wallpaperbackup.WallpaperEventLogger.WALLPAPER_LIVE_SYSTEM;
34 
35 import static com.google.common.truth.Truth.assertThat;
36 
37 import static org.junit.Assert.assertEquals;
38 import static org.mockito.ArgumentMatchers.any;
39 import static org.mockito.ArgumentMatchers.anyBoolean;
40 import static org.mockito.ArgumentMatchers.anyInt;
41 import static org.mockito.ArgumentMatchers.eq;
42 import static org.mockito.Mockito.never;
43 import static org.mockito.Mockito.times;
44 import static org.mockito.Mockito.verify;
45 import static org.mockito.Mockito.when;
46 
47 import android.app.WallpaperInfo;
48 import android.app.WallpaperManager;
49 import android.app.backup.BackupAnnotations;
50 import android.app.backup.BackupManager;
51 import android.app.backup.BackupRestoreEventLogger;
52 import android.app.backup.BackupRestoreEventLogger.DataTypeResult;
53 import android.app.backup.FullBackupDataOutput;
54 import android.content.ComponentName;
55 import android.content.Context;
56 import android.content.Intent;
57 import android.content.pm.PackageManager;
58 import android.content.pm.ResolveInfo;
59 import android.os.FileUtils;
60 import android.os.ParcelFileDescriptor;
61 import android.os.UserHandle;
62 import android.service.wallpaper.WallpaperService;
63 import android.util.Xml;
64 
65 import androidx.test.InstrumentationRegistry;
66 import androidx.test.core.app.ApplicationProvider;
67 import androidx.test.runner.AndroidJUnit4;
68 
69 import com.android.internal.content.PackageMonitor;
70 import com.android.modules.utils.TypedXmlSerializer;
71 import com.android.wallpaperbackup.utils.ContextWithServiceOverrides;
72 
73 import org.junit.After;
74 import org.junit.Before;
75 import org.junit.Rule;
76 import org.junit.Test;
77 import org.junit.rules.TemporaryFolder;
78 import org.junit.runner.RunWith;
79 import org.mockito.Mock;
80 import org.mockito.MockitoAnnotations;
81 
82 import java.io.File;
83 import java.io.FileInputStream;
84 import java.io.FileOutputStream;
85 import java.io.IOException;
86 import java.util.ArrayList;
87 import java.util.List;
88 import java.util.Optional;
89 
90 @RunWith(AndroidJUnit4.class)
91 public class WallpaperBackupAgentTest {
92     private static final String TEST_WALLPAPER_PACKAGE = "wallpaper_package";
93 
94     private static final int TEST_SYSTEM_WALLPAPER_ID = 1;
95     private static final int TEST_LOCK_WALLPAPER_ID = 2;
96     private static final int NO_LOCK_WALLPAPER_ID = -1;
97     // An arbitrary user.
98     private static final UserHandle USER_HANDLE = new UserHandle(15);
99 
100     @Mock
101     private FullBackupDataOutput mOutput;
102     @Mock
103     private WallpaperManager mWallpaperManager;
104     @Mock
105     private Context mMockContext;
106     @Mock
107     private BackupManager mBackupManager;
108 
109     @Rule
110     public TemporaryFolder mTemporaryFolder = new TemporaryFolder();
111 
112     private ContextWithServiceOverrides mContext;
113     private IsolatedWallpaperBackupAgent mWallpaperBackupAgent;
114     private ComponentName mWallpaperComponent;
115 
116     @Before
setUp()117     public void setUp() {
118         MockitoAnnotations.initMocks(this);
119 
120         when(mWallpaperManager.isLockscreenLiveWallpaperEnabled()).thenReturn(true);
121         when(mWallpaperManager.isWallpaperBackupEligible(eq(FLAG_SYSTEM))).thenReturn(true);
122         when(mWallpaperManager.isWallpaperBackupEligible(eq(FLAG_LOCK))).thenReturn(true);
123 
124         mContext = new ContextWithServiceOverrides(ApplicationProvider.getApplicationContext());
125         mContext.injectSystemService(WallpaperManager.class, mWallpaperManager);
126 
127         mWallpaperBackupAgent = new IsolatedWallpaperBackupAgent();
128         mWallpaperBackupAgent.attach(mContext);
129         mWallpaperBackupAgent.onCreate(USER_HANDLE, BackupAnnotations.BackupDestination.CLOUD,
130                 BackupAnnotations.OperationType.BACKUP);
131 
132         mWallpaperComponent = new ComponentName(TEST_WALLPAPER_PACKAGE, "");
133     }
134 
135     @After
tearDown()136     public void tearDown() {
137         FileUtils.deleteContents(mContext.getFilesDir());
138     }
139 
140     @Test
testOnFullBackup_backsUpEmptyFile()141     public void testOnFullBackup_backsUpEmptyFile() throws IOException {
142         mWallpaperBackupAgent.onFullBackup(mOutput);
143 
144         assertThat(getBackedUpFileOptional("empty").isPresent()).isTrue();
145     }
146 
147     @Test
testOnFullBackup_noExistingInfoStage_backsUpInfoFile()148     public void testOnFullBackup_noExistingInfoStage_backsUpInfoFile() throws Exception {
149         mockWallpaperInfoFileWithContents("fake info file");
150 
151         mWallpaperBackupAgent.onFullBackup(mOutput);
152 
153         assertFileContentEquals(getBackedUpFileOptional(WALLPAPER_INFO_STAGE).get(),
154                 "fake info file");
155     }
156 
157     @Test
testOnFullBackup_existingInfoStage_noChange_backsUpAlreadyStagedInfoFile()158     public void testOnFullBackup_existingInfoStage_noChange_backsUpAlreadyStagedInfoFile()
159             throws Exception {
160         // Do a backup first so the info file is staged.
161         mockWallpaperInfoFileWithContents("old info file");
162         // Provide system and lock wallpapers but don't change them in between backups.
163         mockSystemWallpaperFileWithContents("system wallpaper");
164         mockLockWallpaperFileWithContents("lock wallpaper");
165         mWallpaperBackupAgent.onFullBackup(mOutput);
166         mWallpaperBackupAgent.mBackedUpFiles.clear();
167         // This new wallpaper should be ignored since the ID of neither wallpaper changed.
168         mockWallpaperInfoFileWithContents("new info file");
169 
170         mWallpaperBackupAgent.onFullBackup(mOutput);
171 
172         assertFileContentEquals(getBackedUpFileOptional(WALLPAPER_INFO_STAGE).get(),
173                 "old info file");
174     }
175 
176     @Test
testOnFullBackup_existingInfoStage_sysChanged_backsUpNewInfoFile()177     public void testOnFullBackup_existingInfoStage_sysChanged_backsUpNewInfoFile()
178             throws Exception {
179         // Do a backup first so the backed up system wallpaper ID is persisted to disk.
180         mockWallpaperInfoFileWithContents("old info file");
181         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
182         mWallpaperBackupAgent.onFullBackup(mOutput);
183         mWallpaperBackupAgent.mBackedUpFiles.clear();
184         // Mock that the user changed the system wallpaper.
185         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID + 1, TEST_LOCK_WALLPAPER_ID);
186         mockWallpaperInfoFileWithContents("new info file");
187 
188         mWallpaperBackupAgent.onFullBackup(mOutput);
189 
190         assertFileContentEquals(getBackedUpFileOptional(WALLPAPER_INFO_STAGE).get(),
191                 "new info file");
192     }
193 
194     @Test
testOnFullBackup_existingInfoStage_lockChanged_backsUpNewInfoFile()195     public void testOnFullBackup_existingInfoStage_lockChanged_backsUpNewInfoFile()
196             throws Exception {
197         // Do a backup first so the backed up lock wallpaper ID is persisted to disk.
198         mockWallpaperInfoFileWithContents("old info file");
199         mockLockWallpaperFileWithContents("lock wallpaper");
200         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
201         mWallpaperBackupAgent.onFullBackup(mOutput);
202         mWallpaperBackupAgent.mBackedUpFiles.clear();
203         // Mock that the user changed the system wallpaper.
204         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID + 1);
205         mockWallpaperInfoFileWithContents("new info file");
206 
207         mWallpaperBackupAgent.onFullBackup(mOutput);
208 
209         assertFileContentEquals(getBackedUpFileOptional(WALLPAPER_INFO_STAGE).get(),
210                 "new info file");
211     }
212 
213     @Test
testOnFullBackup_systemWallpaperNotEligible_doesNotBackUpSystemWallpaper()214     public void testOnFullBackup_systemWallpaperNotEligible_doesNotBackUpSystemWallpaper()
215             throws Exception {
216         when(mWallpaperManager.isWallpaperBackupEligible(eq(FLAG_SYSTEM))).thenReturn(false);
217         mockSystemWallpaperFileWithContents("system wallpaper");
218         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, NO_LOCK_WALLPAPER_ID);
219 
220         mWallpaperBackupAgent.onFullBackup(mOutput);
221 
222         assertThat(getBackedUpFileOptional(SYSTEM_WALLPAPER_STAGE).isPresent()).isFalse();
223     }
224 
225     @Test
testOnFullBackup_existingSystemStage_noSysChange_backsUpAlreadyStagedFile()226     public void testOnFullBackup_existingSystemStage_noSysChange_backsUpAlreadyStagedFile()
227             throws Exception {
228         // Do a backup first so that a stage file is created.
229         mockSystemWallpaperFileWithContents("system wallpaper");
230         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, NO_LOCK_WALLPAPER_ID);
231         mWallpaperBackupAgent.onFullBackup(mOutput);
232         mWallpaperBackupAgent.mBackedUpFiles.clear();
233         // This new file should be ignored since the ID of the wallpaper did not change.
234         mockSystemWallpaperFileWithContents("new system wallpaper");
235 
236         mWallpaperBackupAgent.onFullBackup(mOutput);
237 
238         assertFileContentEquals(getBackedUpFileOptional(SYSTEM_WALLPAPER_STAGE).get(),
239                 "system wallpaper");
240     }
241 
242     @Test
testOnFullBackup_existingSystemStage_sysChanged_backsUpNewSystemWallpaper()243     public void testOnFullBackup_existingSystemStage_sysChanged_backsUpNewSystemWallpaper()
244             throws Exception {
245         // Do a backup first so that a stage file is created.
246         mockSystemWallpaperFileWithContents("system wallpaper");
247         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, NO_LOCK_WALLPAPER_ID);
248         mWallpaperBackupAgent.onFullBackup(mOutput);
249         mWallpaperBackupAgent.mBackedUpFiles.clear();
250         // Mock that the system wallpaper was changed by the user.
251         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID + 1, NO_LOCK_WALLPAPER_ID);
252         mockSystemWallpaperFileWithContents("new system wallpaper");
253 
254         mWallpaperBackupAgent.onFullBackup(mOutput);
255 
256         assertFileContentEquals(getBackedUpFileOptional(SYSTEM_WALLPAPER_STAGE).get(),
257                 "new system wallpaper");
258     }
259 
260     @Test
testOnFullBackup_noExistingSystemStage_backsUpSystemWallpaper()261     public void testOnFullBackup_noExistingSystemStage_backsUpSystemWallpaper()
262             throws Exception {
263         mockSystemWallpaperFileWithContents("system wallpaper");
264         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, NO_LOCK_WALLPAPER_ID);
265 
266         mWallpaperBackupAgent.onFullBackup(mOutput);
267 
268         assertFileContentEquals(getBackedUpFileOptional(SYSTEM_WALLPAPER_STAGE).get(),
269                 "system wallpaper");
270     }
271 
272     @Test
testOnFullBackup_lockWallpaperNotEligible_doesNotBackUpLockWallpaper()273     public void testOnFullBackup_lockWallpaperNotEligible_doesNotBackUpLockWallpaper()
274             throws Exception {
275         when(mWallpaperManager.isWallpaperBackupEligible(eq(FLAG_LOCK))).thenReturn(false);
276         mockLockWallpaperFileWithContents("lock wallpaper");
277         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
278 
279         mWallpaperBackupAgent.onFullBackup(mOutput);
280 
281         assertThat(getBackedUpFileOptional(LOCK_WALLPAPER_STAGE).isPresent()).isFalse();
282     }
283 
284     @Test
testOnFullBackup_existingLockStage_lockWallpaperRemovedByUser_NotBackUpOldStage()285     public void testOnFullBackup_existingLockStage_lockWallpaperRemovedByUser_NotBackUpOldStage()
286             throws Exception {
287         // Do a backup first so that a stage file is created.
288         mockLockWallpaperFileWithContents("lock wallpaper");
289         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
290         mWallpaperBackupAgent.onFullBackup(mOutput);
291         mWallpaperBackupAgent.mBackedUpFiles.clear();
292         // Mock the ID of the lock wallpaper to indicate it's not set.
293         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, NO_LOCK_WALLPAPER_ID);
294 
295         mWallpaperBackupAgent.onFullBackup(mOutput);
296 
297         assertThat(getBackedUpFileOptional(LOCK_WALLPAPER_STAGE).isPresent()).isFalse();
298     }
299 
300     @Test
testOnFullBackup_existingLockStage_lockWallpaperRemovedByUser_deletesExistingStage()301     public void testOnFullBackup_existingLockStage_lockWallpaperRemovedByUser_deletesExistingStage()
302             throws Exception {
303         // Do a backup first so that a stage file is created.
304         mockLockWallpaperFileWithContents("lock wallpaper");
305         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
306         mWallpaperBackupAgent.onFullBackup(mOutput);
307         mWallpaperBackupAgent.mBackedUpFiles.clear();
308         // Mock the ID of the lock wallpaper to indicate it's not set.
309         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, NO_LOCK_WALLPAPER_ID);
310 
311         mWallpaperBackupAgent.onFullBackup(mOutput);
312 
313         assertThat(new File(mContext.getFilesDir(), LOCK_WALLPAPER_STAGE).exists()).isFalse();
314     }
315 
316     @Test
testOnFullBackup_existingLockStage_noLockChange_backsUpAlreadyStagedFile()317     public void testOnFullBackup_existingLockStage_noLockChange_backsUpAlreadyStagedFile()
318             throws Exception {
319         // Do a backup first so that a stage file is created.
320         mockLockWallpaperFileWithContents("old lock wallpaper");
321         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
322         mWallpaperBackupAgent.onFullBackup(mOutput);
323         mWallpaperBackupAgent.mBackedUpFiles.clear();
324         // This new file should be ignored since the ID of the wallpaper did not change.
325         mockLockWallpaperFileWithContents("new lock wallpaper");
326 
327         mWallpaperBackupAgent.onFullBackup(mOutput);
328 
329         assertFileContentEquals(getBackedUpFileOptional(LOCK_WALLPAPER_STAGE).get(),
330                 "old lock wallpaper");
331     }
332 
333     @Test
testOnFullBackup_existingLockStage_lockChanged_backsUpNewLockWallpaper()334     public void testOnFullBackup_existingLockStage_lockChanged_backsUpNewLockWallpaper()
335             throws Exception {
336         // Do a backup first so that a stage file is created.
337         mockLockWallpaperFileWithContents("old lock wallpaper");
338         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
339         mWallpaperBackupAgent.onFullBackup(mOutput);
340         mWallpaperBackupAgent.mBackedUpFiles.clear();
341         // Mock that the lock wallpaper was changed by the user.
342         mockLockWallpaperFileWithContents("new lock wallpaper");
343         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID + 1);
344 
345         mWallpaperBackupAgent.onFullBackup(mOutput);
346 
347         assertFileContentEquals(getBackedUpFileOptional(LOCK_WALLPAPER_STAGE).get(),
348                 "new lock wallpaper");
349     }
350 
351     @Test
testOnFullBackup_noExistingLockStage_backsUpLockWallpaper()352     public void testOnFullBackup_noExistingLockStage_backsUpLockWallpaper()
353             throws Exception {
354         mockLockWallpaperFileWithContents("lock wallpaper");
355         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
356 
357         mWallpaperBackupAgent.onFullBackup(mOutput);
358 
359         assertFileContentEquals(getBackedUpFileOptional(LOCK_WALLPAPER_STAGE).get(),
360                 "lock wallpaper");
361     }
362 
363     @Test
testUpdateWallpaperComponent_doesApplyLater()364     public void testUpdateWallpaperComponent_doesApplyLater() throws IOException {
365         mWallpaperBackupAgent.mIsDeviceInRestore = true;
366 
367         mWallpaperBackupAgent.updateWallpaperComponent(mWallpaperComponent,
368                 /* applyToLock */ true, FLAG_LOCK | FLAG_SYSTEM);
369 
370         // Imitate wallpaper component installation.
371         mWallpaperBackupAgent.mWallpaperPackageMonitor.onPackageAdded(TEST_WALLPAPER_PACKAGE,
372                 /* uid */0);
373         if (mWallpaperManager.isLockscreenLiveWallpaperEnabled()) {
374             verify(mWallpaperManager, times(1))
375                     .setWallpaperComponentWithFlags(mWallpaperComponent, FLAG_LOCK | FLAG_SYSTEM);
376             verify(mWallpaperManager, never())
377                     .setWallpaperComponentWithFlags(mWallpaperComponent, FLAG_SYSTEM);
378             verify(mWallpaperManager, never())
379                     .setWallpaperComponentWithFlags(mWallpaperComponent, FLAG_LOCK);
380             verify(mWallpaperManager, never()).clear(anyInt());
381         } else {
382             verify(mWallpaperManager, times(1)).setWallpaperComponent(mWallpaperComponent);
383             verify(mWallpaperManager, times(1)).clear(eq(FLAG_LOCK));
384         }
385     }
386 
387     @Test
testUpdateWallpaperComponent_applyToLockFalse_doesApplyLaterOnlyToMainScreen()388     public void testUpdateWallpaperComponent_applyToLockFalse_doesApplyLaterOnlyToMainScreen()
389             throws IOException {
390         mWallpaperBackupAgent.mIsDeviceInRestore = true;
391 
392         mWallpaperBackupAgent.updateWallpaperComponent(mWallpaperComponent,
393                 /* applyToLock */ false, FLAG_SYSTEM);
394 
395         // Imitate wallpaper component installation.
396         mWallpaperBackupAgent.mWallpaperPackageMonitor.onPackageAdded(TEST_WALLPAPER_PACKAGE,
397                 /* uid */0);
398 
399         if (mWallpaperManager.isLockscreenLiveWallpaperEnabled()) {
400             verify(mWallpaperManager, times(1))
401                     .setWallpaperComponentWithFlags(mWallpaperComponent, FLAG_SYSTEM);
402             verify(mWallpaperManager, never())
403                     .setWallpaperComponentWithFlags(mWallpaperComponent, FLAG_LOCK);
404             verify(mWallpaperManager, never())
405                     .setWallpaperComponentWithFlags(mWallpaperComponent, FLAG_LOCK | FLAG_SYSTEM);
406             verify(mWallpaperManager, never()).clear(anyInt());
407         } else {
408             verify(mWallpaperManager, times(1)).setWallpaperComponent(mWallpaperComponent);
409             verify(mWallpaperManager, never()).clear(eq(FLAG_LOCK));
410         }
411     }
412 
413     @Test
testUpdateWallpaperComponent_deviceNotInRestore_doesNotApply()414     public void testUpdateWallpaperComponent_deviceNotInRestore_doesNotApply()
415             throws IOException {
416         mWallpaperBackupAgent.mIsDeviceInRestore = false;
417 
418         mWallpaperBackupAgent.updateWallpaperComponent(mWallpaperComponent,
419                 /* applyToLock */ true, FLAG_LOCK | FLAG_SYSTEM);
420 
421         // Imitate wallpaper component installation.
422         mWallpaperBackupAgent.mWallpaperPackageMonitor.onPackageAdded(TEST_WALLPAPER_PACKAGE,
423                 /* uid */0);
424 
425         verify(mWallpaperManager, never()).setWallpaperComponent(mWallpaperComponent);
426         verify(mWallpaperManager, never()).clear(eq(FLAG_LOCK));
427     }
428 
429     @Test
testUpdateWallpaperComponent_differentPackageInstalled_doesNotApply()430     public void testUpdateWallpaperComponent_differentPackageInstalled_doesNotApply()
431             throws IOException {
432         mWallpaperBackupAgent.mIsDeviceInRestore = false;
433 
434         mWallpaperBackupAgent.updateWallpaperComponent(mWallpaperComponent,
435                 /* applyToLock */ true, FLAG_LOCK | FLAG_SYSTEM);
436 
437         // Imitate "wrong" wallpaper component installation.
438         mWallpaperBackupAgent.mWallpaperPackageMonitor.onPackageAdded(/* packageName */"",
439                 /* uid */0);
440 
441         verify(mWallpaperManager, never()).setWallpaperComponent(mWallpaperComponent);
442         verify(mWallpaperManager, never()).clear(eq(FLAG_LOCK));
443     }
444 
445     @Test
testOnFullBackup_systemWallpaperImgSuccess_logsSuccess()446     public void testOnFullBackup_systemWallpaperImgSuccess_logsSuccess() throws Exception {
447         mockSystemWallpaperFileWithContents("system wallpaper");
448         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, NO_LOCK_WALLPAPER_ID);
449 
450         mWallpaperBackupAgent.onFullBackup(mOutput);
451 
452         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_SYSTEM,
453                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
454         assertThat(result).isNotNull();
455         assertThat(result.getSuccessCount()).isEqualTo(1);
456     }
457 
458     @Test
testOnFullBackup_systemWallpaperImgIneligible_logsFailure()459     public void testOnFullBackup_systemWallpaperImgIneligible_logsFailure() throws Exception {
460         when(mWallpaperManager.isWallpaperBackupEligible(eq(FLAG_SYSTEM))).thenReturn(false);
461         mockSystemWallpaperFileWithContents("system wallpaper");
462         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
463 
464         mWallpaperBackupAgent.onFullBackup(mOutput);
465 
466         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_SYSTEM,
467                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
468         assertThat(result).isNotNull();
469         assertThat(result.getFailCount()).isEqualTo(1);
470         assertThat(result.getErrors()).containsKey(ERROR_INELIGIBLE);
471     }
472 
473     @Test
testOnFullBackup_systemWallpaperImgMissing_logsFailure()474     public void testOnFullBackup_systemWallpaperImgMissing_logsFailure() throws Exception {
475         mWallpaperBackupAgent.onFullBackup(mOutput);
476 
477         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_SYSTEM,
478                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
479         assertThat(result).isNotNull();
480         assertThat(result.getFailCount()).isEqualTo(1);
481         assertThat(result.getErrors()).containsKey(ERROR_NO_WALLPAPER);
482     }
483 
484     @Test
testOnFullBackup_systemWallpaperImgMissingButHasLiveComponent_logsLiveSuccess()485     public void testOnFullBackup_systemWallpaperImgMissingButHasLiveComponent_logsLiveSuccess()
486             throws Exception {
487         mockWallpaperInfoFileWithContents("info file");
488         when(mWallpaperManager.getWallpaperInfo(anyInt())).thenReturn(getFakeWallpaperInfo());
489 
490         mWallpaperBackupAgent.onFullBackup(mOutput);
491 
492         DataTypeResult result = getLoggingResult(WALLPAPER_LIVE_SYSTEM,
493                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
494         assertThat(result).isNotNull();
495         assertThat(result.getSuccessCount()).isEqualTo(1);
496         assertThat(result.getMetadataHash()).isNotNull();
497     }
498 
499     @Test
testOnFullBackup_systemWallpaperImgMissingButHasLiveComponent_logsNothingForImg()500     public void testOnFullBackup_systemWallpaperImgMissingButHasLiveComponent_logsNothingForImg()
501             throws Exception {
502         mockWallpaperInfoFileWithContents("info file");
503         when(mWallpaperManager.getWallpaperInfo(anyInt())).thenReturn(getFakeWallpaperInfo());
504 
505         mWallpaperBackupAgent.onFullBackup(mOutput);
506 
507         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_SYSTEM,
508                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
509         assertThat(result).isNull();
510     }
511 
512     @Test
testOnFullBackup_lockWallpaperImgSuccess_logsSuccess()513     public void testOnFullBackup_lockWallpaperImgSuccess_logsSuccess() throws Exception {
514         mockLockWallpaperFileWithContents("lock wallpaper");
515         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
516 
517         mWallpaperBackupAgent.onFullBackup(mOutput);
518 
519         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_LOCK,
520                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
521         assertThat(result).isNotNull();
522         assertThat(result.getSuccessCount()).isEqualTo(1);
523     }
524 
525     @Test
testOnFullBackup_lockWallpaperImgIneligible_logsFailure()526     public void testOnFullBackup_lockWallpaperImgIneligible_logsFailure() throws Exception {
527         when(mWallpaperManager.isWallpaperBackupEligible(eq(FLAG_LOCK))).thenReturn(false);
528         mockLockWallpaperFileWithContents("lock wallpaper");
529         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
530 
531         mWallpaperBackupAgent.onFullBackup(mOutput);
532 
533         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_LOCK,
534                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
535         assertThat(result).isNotNull();
536         assertThat(result.getFailCount()).isEqualTo(1);
537         assertThat(result.getErrors()).containsKey(ERROR_INELIGIBLE);
538     }
539 
540     @Test
testOnFullBackup_lockWallpaperImgMissing_logsFailure()541     public void testOnFullBackup_lockWallpaperImgMissing_logsFailure() throws Exception {
542         mWallpaperBackupAgent.onFullBackup(mOutput);
543 
544         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_LOCK,
545                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
546         assertThat(result).isNotNull();
547         assertThat(result.getFailCount()).isEqualTo(1);
548         assertThat(result.getErrors()).containsKey(ERROR_NO_WALLPAPER);
549     }
550 
551     @Test
testOnFullBackup_lockWallpaperImgMissingButHasLiveComponent_logsLiveSuccess()552     public void testOnFullBackup_lockWallpaperImgMissingButHasLiveComponent_logsLiveSuccess()
553             throws Exception {
554         mockWallpaperInfoFileWithContents("info file");
555         when(mWallpaperManager.getWallpaperInfo(anyInt())).thenReturn(getFakeWallpaperInfo());
556 
557         mWallpaperBackupAgent.onFullBackup(mOutput);
558 
559         DataTypeResult result = getLoggingResult(WALLPAPER_LIVE_LOCK,
560                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
561         assertThat(result).isNotNull();
562         assertThat(result.getSuccessCount()).isEqualTo(1);
563         assertThat(result.getMetadataHash()).isNotNull();
564     }
565 
566     @Test
testOnFullBackup_lockWallpaperImgMissingButHasLiveComponent_logsNothingForImg()567     public void testOnFullBackup_lockWallpaperImgMissingButHasLiveComponent_logsNothingForImg()
568             throws Exception {
569         mockWallpaperInfoFileWithContents("info file");
570         when(mWallpaperManager.getWallpaperInfo(anyInt())).thenReturn(getFakeWallpaperInfo());
571 
572         mWallpaperBackupAgent.onFullBackup(mOutput);
573 
574         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_LOCK,
575                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
576         assertThat(result).isNull();
577     }
578 
579 
580     @Test
testOnFullBackup_exceptionThrown_logsException()581     public void testOnFullBackup_exceptionThrown_logsException() throws Exception {
582         when(mWallpaperManager.isWallpaperBackupEligible(anyInt())).thenThrow(
583                 new RuntimeException());
584         mWallpaperBackupAgent.onFullBackup(mOutput);
585 
586         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_LOCK,
587                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
588         assertThat(result).isNotNull();
589         assertThat(result.getFailCount()).isEqualTo(1);
590         assertThat(result.getErrors()).containsKey(RuntimeException.class.getName());
591     }
592 
593     @Test
testOnFullBackup_lastBackupOverQuota_logsLockFailure()594     public void testOnFullBackup_lastBackupOverQuota_logsLockFailure() throws Exception {
595         mockSystemWallpaperFileWithContents("system wallpaper");
596         mockLockWallpaperFileWithContents("lock wallpaper");
597         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
598         markAgentAsOverQuota();
599 
600         mWallpaperBackupAgent.onFullBackup(mOutput);
601 
602         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_LOCK,
603                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
604         assertThat(result).isNotNull();
605         assertThat(result.getFailCount()).isEqualTo(1);
606         assertThat(result.getErrors()).containsKey(ERROR_QUOTA_EXCEEDED);
607     }
608 
609     @Test
testOnFullBackup_lastBackupOverQuota_logsSystemSuccess()610     public void testOnFullBackup_lastBackupOverQuota_logsSystemSuccess() throws Exception {
611         mockSystemWallpaperFileWithContents("system wallpaper");
612         mockLockWallpaperFileWithContents("lock wallpaper");
613         mockCurrentWallpaperIds(TEST_SYSTEM_WALLPAPER_ID, TEST_LOCK_WALLPAPER_ID);
614         markAgentAsOverQuota();
615 
616         mWallpaperBackupAgent.onFullBackup(mOutput);
617 
618         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_SYSTEM,
619                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
620         assertThat(result).isNotNull();
621         assertThat(result.getSuccessCount()).isEqualTo(1);
622     }
623 
624     @Test
testOnRestore_systemWallpaperImgSuccess_logsSuccess()625     public void testOnRestore_systemWallpaperImgSuccess_logsSuccess() throws Exception {
626         mockStagedWallpaperFile(WALLPAPER_INFO_STAGE);
627         mockStagedWallpaperFile(SYSTEM_WALLPAPER_STAGE);
628         mWallpaperBackupAgent.onCreate(USER_HANDLE, BackupAnnotations.BackupDestination.CLOUD,
629                 BackupAnnotations.OperationType.RESTORE);
630 
631         mWallpaperBackupAgent.onRestoreFinished();
632 
633         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_SYSTEM,
634                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
635         assertThat(result).isNotNull();
636         assertThat(result.getSuccessCount()).isEqualTo(1);
637 
638         if (mWallpaperManager.isLockscreenLiveWallpaperEnabled()) {
639             result = getLoggingResult(WALLPAPER_IMG_LOCK,
640                     mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
641             assertThat(result).isNotNull();
642             assertThat(result.getSuccessCount()).isEqualTo(1);
643         }
644     }
645 
646     @Test
testOnRestore_lockWallpaperImgSuccess_logsSuccess()647     public void testOnRestore_lockWallpaperImgSuccess_logsSuccess() throws Exception {
648         mockStagedWallpaperFile(WALLPAPER_INFO_STAGE);
649         mockStagedWallpaperFile(LOCK_WALLPAPER_STAGE);
650         mWallpaperBackupAgent.onCreate(USER_HANDLE, BackupAnnotations.BackupDestination.CLOUD,
651                 BackupAnnotations.OperationType.RESTORE);
652 
653         mWallpaperBackupAgent.onRestoreFinished();
654 
655         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_LOCK,
656                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
657         assertThat(result).isNotNull();
658         assertThat(result.getSuccessCount()).isEqualTo(1);
659     }
660 
661     @Test
testOnRestore_systemWallpaperImgMissingAndNoLive_logsFailure()662     public void testOnRestore_systemWallpaperImgMissingAndNoLive_logsFailure() throws Exception {
663         mockStagedWallpaperFile(WALLPAPER_INFO_STAGE);
664         mockStagedWallpaperFile(LOCK_WALLPAPER_STAGE);
665         mWallpaperBackupAgent.onCreate(USER_HANDLE, BackupAnnotations.BackupDestination.CLOUD,
666                 BackupAnnotations.OperationType.RESTORE);
667 
668         mWallpaperBackupAgent.onRestoreFinished();
669 
670         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_SYSTEM,
671                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
672         assertThat(result).isNotNull();
673         assertThat(result.getFailCount()).isEqualTo(1);
674         assertThat(result.getErrors()).containsKey(ERROR_NO_WALLPAPER);
675 
676     }
677 
678     @Test
testOnRestore_wallpaperImgMissingAndNoLive_logsFailure()679     public void testOnRestore_wallpaperImgMissingAndNoLive_logsFailure() throws Exception {
680         mockStagedWallpaperFile(WALLPAPER_INFO_STAGE);
681         mWallpaperBackupAgent.onCreate(USER_HANDLE, BackupAnnotations.BackupDestination.CLOUD,
682                 BackupAnnotations.OperationType.RESTORE);
683 
684         mWallpaperBackupAgent.onRestoreFinished();
685 
686         for (String wallpaper: List.of(WALLPAPER_IMG_LOCK, WALLPAPER_IMG_SYSTEM)) {
687             DataTypeResult result = getLoggingResult(wallpaper,
688                     mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
689             assertThat(result).isNotNull();
690             assertThat(result.getFailCount()).isEqualTo(1);
691             assertThat(result.getErrors()).containsKey(ERROR_NO_WALLPAPER);
692         }
693     }
694 
695     @Test
testOnRestore_wallpaperInfoMissing_logsFailure()696     public void testOnRestore_wallpaperInfoMissing_logsFailure() throws Exception {
697         mockStagedWallpaperFile(SYSTEM_WALLPAPER_STAGE);
698         mWallpaperBackupAgent.onCreate(USER_HANDLE, BackupAnnotations.BackupDestination.CLOUD,
699                 BackupAnnotations.OperationType.RESTORE);
700 
701         mWallpaperBackupAgent.onRestoreFinished();
702 
703         DataTypeResult result = getLoggingResult(WALLPAPER_IMG_SYSTEM,
704                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
705         assertThat(result).isNotNull();
706         assertThat(result.getFailCount()).isEqualTo(1);
707         assertThat(result.getErrors()).containsKey(ERROR_NO_METADATA);
708     }
709 
710     @Test
testOnRestore_imgMissingButWallpaperInfoHasLive_doesNotLogImg()711     public void testOnRestore_imgMissingButWallpaperInfoHasLive_doesNotLogImg() throws Exception {
712         mockRestoredLiveWallpaperFile();
713         mWallpaperBackupAgent.onCreate(USER_HANDLE, BackupAnnotations.BackupDestination.CLOUD,
714                 BackupAnnotations.OperationType.RESTORE);
715 
716         mWallpaperBackupAgent.onRestoreFinished();
717 
718         DataTypeResult system = getLoggingResult(WALLPAPER_IMG_SYSTEM,
719                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
720         DataTypeResult lock = getLoggingResult(WALLPAPER_IMG_LOCK,
721                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
722         assertThat(system).isNull();
723         assertThat(lock).isNull();
724     }
725 
726     @Test
testOnRestore_throwsException_logsErrors()727     public void testOnRestore_throwsException_logsErrors() throws Exception {
728         when(mWallpaperManager.setStream(any(), any(), anyBoolean(), anyInt())).thenThrow(
729                 new RuntimeException());
730         mockStagedWallpaperFile(SYSTEM_WALLPAPER_STAGE);
731         mockStagedWallpaperFile(WALLPAPER_INFO_STAGE);
732         mWallpaperBackupAgent.onCreate(USER_HANDLE, BackupAnnotations.BackupDestination.CLOUD,
733                 BackupAnnotations.OperationType.RESTORE);
734 
735         mWallpaperBackupAgent.onRestoreFinished();
736 
737         DataTypeResult system = getLoggingResult(WALLPAPER_IMG_SYSTEM,
738                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
739         DataTypeResult lock = getLoggingResult(WALLPAPER_IMG_LOCK,
740                 mWallpaperBackupAgent.getBackupRestoreEventLogger().getLoggingResults());
741         assertThat(system).isNotNull();
742         assertThat(system.getFailCount()).isEqualTo(1);
743         assertThat(system.getErrors()).containsKey(RuntimeException.class.getName());
744         assertThat(lock).isNotNull();
745         assertThat(lock.getFailCount()).isEqualTo(1);
746         assertThat(lock.getErrors()).containsKey(RuntimeException.class.getName());
747     }
748 
749     @Test
testUpdateWallpaperComponent_delayedRestore_logsSuccess()750     public void testUpdateWallpaperComponent_delayedRestore_logsSuccess() throws Exception {
751         mWallpaperBackupAgent.mIsDeviceInRestore = true;
752         when(mWallpaperManager.setWallpaperComponent(any())).thenReturn(true);
753         when(mWallpaperManager.setWallpaperComponentWithFlags(any(), eq(FLAG_LOCK | FLAG_SYSTEM)))
754                 .thenReturn(true);
755         BackupRestoreEventLogger logger = new BackupRestoreEventLogger(
756                 BackupAnnotations.OperationType.RESTORE);
757         when(mBackupManager.getDelayedRestoreLogger()).thenReturn(logger);
758         mWallpaperBackupAgent.setBackupManagerForTesting(mBackupManager);
759 
760         mWallpaperBackupAgent.updateWallpaperComponent(mWallpaperComponent,
761                 /* applyToLock */ true, FLAG_LOCK | FLAG_SYSTEM);
762         // Imitate wallpaper component installation.
763         mWallpaperBackupAgent.mWallpaperPackageMonitor.onPackageAdded(TEST_WALLPAPER_PACKAGE,
764                 /* uid */0);
765 
766         DataTypeResult system = getLoggingResult(WALLPAPER_LIVE_SYSTEM, logger.getLoggingResults());
767         DataTypeResult lock = getLoggingResult(WALLPAPER_LIVE_LOCK, logger.getLoggingResults());
768         assertThat(system).isNotNull();
769         assertThat(system.getSuccessCount()).isEqualTo(1);
770         assertThat(lock).isNotNull();
771         assertThat(lock.getSuccessCount()).isEqualTo(1);
772     }
773 
774 
775     @Test
testUpdateWallpaperComponent_delayedRestoreFails_logsFailure()776     public void testUpdateWallpaperComponent_delayedRestoreFails_logsFailure() throws Exception {
777         mWallpaperBackupAgent.mIsDeviceInRestore = true;
778         when(mWallpaperManager.setWallpaperComponent(any())).thenReturn(false);
779         BackupRestoreEventLogger logger = new BackupRestoreEventLogger(
780                 BackupAnnotations.OperationType.RESTORE);
781         when(mBackupManager.getDelayedRestoreLogger()).thenReturn(logger);
782         mWallpaperBackupAgent.setBackupManagerForTesting(mBackupManager);
783 
784         mWallpaperBackupAgent.updateWallpaperComponent(mWallpaperComponent,
785                 /* applyToLock */ true, FLAG_LOCK | FLAG_SYSTEM);
786         // Imitate wallpaper component installation.
787         mWallpaperBackupAgent.mWallpaperPackageMonitor.onPackageAdded(TEST_WALLPAPER_PACKAGE,
788                 /* uid */0);
789 
790         DataTypeResult system = getLoggingResult(WALLPAPER_LIVE_SYSTEM, logger.getLoggingResults());
791         assertThat(system).isNotNull();
792         assertThat(system.getFailCount()).isEqualTo(1);
793         assertThat(system.getErrors()).containsKey(
794                 WallpaperEventLogger.ERROR_SET_COMPONENT_EXCEPTION);
795     }
796 
797     @Test
testUpdateWallpaperComponent_delayedRestore_packageNotInstalled_logsFailure()798     public void testUpdateWallpaperComponent_delayedRestore_packageNotInstalled_logsFailure()
799             throws Exception {
800         mWallpaperBackupAgent.mIsDeviceInRestore = false;
801         BackupRestoreEventLogger logger = new BackupRestoreEventLogger(
802                 BackupAnnotations.OperationType.RESTORE);
803         when(mBackupManager.getDelayedRestoreLogger()).thenReturn(logger);
804         mWallpaperBackupAgent.setBackupManagerForTesting(mBackupManager);
805 
806         mWallpaperBackupAgent.updateWallpaperComponent(mWallpaperComponent,
807                 /* applyToLock */ true, FLAG_LOCK | FLAG_SYSTEM);
808 
809         // Imitate wallpaper component installation.
810         mWallpaperBackupAgent.mWallpaperPackageMonitor.onPackageAdded(TEST_WALLPAPER_PACKAGE,
811                 /* uid */0);
812 
813         DataTypeResult system = getLoggingResult(WALLPAPER_LIVE_SYSTEM, logger.getLoggingResults());
814         DataTypeResult lock = getLoggingResult(WALLPAPER_LIVE_LOCK, logger.getLoggingResults());
815         assertThat(system).isNotNull();
816         assertThat(system.getFailCount()).isEqualTo(1);
817         assertThat(system.getErrors()).containsKey(
818                 WallpaperEventLogger.ERROR_LIVE_PACKAGE_NOT_INSTALLED);
819         assertThat(lock).isNotNull();
820         assertThat(lock.getFailCount()).isEqualTo(1);
821         assertThat(lock.getErrors()).containsKey(
822                 WallpaperEventLogger.ERROR_LIVE_PACKAGE_NOT_INSTALLED);
823     }
824 
mockCurrentWallpaperIds(int systemWallpaperId, int lockWallpaperId)825     private void mockCurrentWallpaperIds(int systemWallpaperId, int lockWallpaperId) {
826         when(mWallpaperManager.getWallpaperId(eq(FLAG_SYSTEM))).thenReturn(systemWallpaperId);
827         when(mWallpaperManager.getWallpaperId(eq(FLAG_LOCK))).thenReturn(lockWallpaperId);
828     }
829 
createTemporaryFileWithContentString(String contents)830     private File createTemporaryFileWithContentString(String contents) throws Exception {
831         File file = mTemporaryFolder.newFile();
832         try (FileOutputStream outputStream = new FileOutputStream(file)) {
833             outputStream.write(contents.getBytes());
834         }
835         return file;
836     }
837 
assertFileContentEquals(File file, String expected)838     private void assertFileContentEquals(File file, String expected) throws Exception {
839         try (FileInputStream inputStream = new FileInputStream(file)) {
840             assertThat(new String(inputStream.readAllBytes())).isEqualTo(expected);
841         }
842     }
843 
getBackedUpFileOptional(String fileName)844     private Optional<File> getBackedUpFileOptional(String fileName) {
845         return mWallpaperBackupAgent.mBackedUpFiles.stream().filter(
846                 file -> file.getName().equals(fileName)).findFirst();
847     }
848 
mockWallpaperInfoFileWithContents(String contents)849     private void mockWallpaperInfoFileWithContents(String contents) throws Exception {
850         File fakeInfoFile = createTemporaryFileWithContentString(contents);
851         when(mWallpaperManager.getWallpaperInfoFile()).thenReturn(
852                 ParcelFileDescriptor.open(fakeInfoFile, MODE_READ_ONLY));
853     }
854 
mockSystemWallpaperFileWithContents(String contents)855     private void mockSystemWallpaperFileWithContents(String contents) throws Exception {
856         File fakeSystemWallpaperFile = createTemporaryFileWithContentString(contents);
857         when(mWallpaperManager.getWallpaperFile(eq(FLAG_SYSTEM), /* cropped = */
858                 eq(false))).thenReturn(
859                 ParcelFileDescriptor.open(fakeSystemWallpaperFile, MODE_READ_ONLY));
860     }
861 
mockLockWallpaperFileWithContents(String contents)862     private void mockLockWallpaperFileWithContents(String contents) throws Exception {
863         File fakeLockWallpaperFile = createTemporaryFileWithContentString(contents);
864         when(mWallpaperManager.getWallpaperFile(eq(FLAG_LOCK), /* cropped = */
865                 eq(false))).thenReturn(
866                 ParcelFileDescriptor.open(fakeLockWallpaperFile, MODE_READ_ONLY));
867     }
868 
mockStagedWallpaperFile(String location)869     private void mockStagedWallpaperFile(String location) throws Exception {
870         File wallpaperFile = new File(mContext.getFilesDir(), location);
871         wallpaperFile.createNewFile();
872     }
873 
mockRestoredLiveWallpaperFile()874     private void mockRestoredLiveWallpaperFile() throws Exception {
875         File wallpaperFile = new File(mContext.getFilesDir(), WALLPAPER_INFO_STAGE);
876         wallpaperFile.createNewFile();
877         FileOutputStream fstream = new FileOutputStream(wallpaperFile, false);
878         TypedXmlSerializer out = Xml.resolveSerializer(fstream);
879         out.startDocument(null, true);
880         out.startTag(null, "wp");
881         out.attribute(null, "component",
882                 getFakeWallpaperInfo().getComponent().flattenToShortString());
883         out.endTag(null, "wp");
884         out.endDocument();
885         fstream.flush();
886         FileUtils.sync(fstream);
887         fstream.close();
888     }
889 
getFakeWallpaperInfo()890     private WallpaperInfo getFakeWallpaperInfo() throws Exception {
891         Context context = InstrumentationRegistry.getTargetContext();
892         Intent intent = new Intent(WallpaperService.SERVICE_INTERFACE);
893         intent.setPackage("com.android.wallpaperbackup.tests");
894         PackageManager pm = context.getPackageManager();
895         List<ResolveInfo> result = pm.queryIntentServices(intent, PackageManager.GET_META_DATA);
896         assertEquals(1, result.size());
897         ResolveInfo info = result.get(0);
898         return new WallpaperInfo(context, info);
899     }
900 
markAgentAsOverQuota()901     private void markAgentAsOverQuota() throws Exception {
902         // Create over quota file to indicate the last backup was over quota
903         File quotaFile = new File(mContext.getFilesDir(), WallpaperBackupAgent.QUOTA_SENTINEL);
904         quotaFile.createNewFile();
905 
906         // Now redo the setup of the agent to pick up the over quota
907         mWallpaperBackupAgent.onCreate(USER_HANDLE, BackupAnnotations.BackupDestination.CLOUD,
908                 BackupAnnotations.OperationType.BACKUP);
909     }
910 
getLoggingResult(String dataType, List<DataTypeResult> results)911     private static DataTypeResult getLoggingResult(String dataType, List<DataTypeResult> results) {
912         for (DataTypeResult result : results) {
913             if ((result.getDataType()).equals(dataType)) {
914                 return result;
915             }
916         }
917         return null;
918     }
919 
920     private class IsolatedWallpaperBackupAgent extends WallpaperBackupAgent {
921         List<File> mBackedUpFiles = new ArrayList<>();
922         PackageMonitor mWallpaperPackageMonitor;
923         boolean mIsDeviceInRestore = false;
924 
925         @Override
backupFile(File file, FullBackupDataOutput data)926         protected void backupFile(File file, FullBackupDataOutput data) {
927             mBackedUpFiles.add(file);
928         }
929 
930         @Override
servicePackageExists(ComponentName comp)931         boolean servicePackageExists(ComponentName comp) {
932             return false;
933         }
934 
935         @Override
isDeviceInRestore()936         boolean isDeviceInRestore() {
937             return mIsDeviceInRestore;
938         }
939 
940         @Override
getWallpaperPackageMonitor(ComponentName componentName, boolean applyToLock, int which)941         PackageMonitor getWallpaperPackageMonitor(ComponentName componentName,
942                 boolean applyToLock, int which) {
943             mWallpaperPackageMonitor = super.getWallpaperPackageMonitor(
944                     componentName, applyToLock, which);
945             return mWallpaperPackageMonitor;
946         }
947 
948         @Override
getBaseContext()949         public Context getBaseContext() {
950             return mMockContext;
951         }
952     }
953 }
954