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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
|
/*
* Copyright (C) 2006 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.unit_tests;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageStats;
import android.content.pm.IPackageManager;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.test.suitebuilder.annotation.Suppress;
import android.util.Log;
import android.os.Handler;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.StatFs;
public class AppCacheTest extends AndroidTestCase {
private static final boolean localLOGV = false;
public static final String TAG="AppCacheTest";
public final long MAX_WAIT_TIME=60*1000;
public final long WAIT_TIME_INCR=10*1000;
private static final int THRESHOLD=5;
private static final int ACTUAL_THRESHOLD=10;
@Override
protected void setUp() throws Exception {
super.setUp();
if(localLOGV) Log.i(TAG, "Cleaning up cache directory first");
cleanUpCacheDirectory();
}
void cleanUpDirectory(File pDir, String dirName) {
File testDir = new File(pDir, dirName);
if(!testDir.exists()) {
return;
}
String fList[] = testDir.list();
for(int i = 0; i < fList.length; i++) {
File file = new File(testDir, fList[i]);
if(file.isDirectory()) {
cleanUpDirectory(testDir, fList[i]);
} else {
file.delete();
}
}
testDir.delete();
}
void cleanUpCacheDirectory() {
File testDir = mContext.getCacheDir();
if(!testDir.exists()) {
return;
}
String fList[] = testDir.list();
if(fList == null) {
testDir.delete();
return;
}
for(int i = 0; i < fList.length; i++) {
File file = new File(testDir, fList[i]);
if(file.isDirectory()) {
cleanUpDirectory(testDir, fList[i]);
} else {
file.delete();
}
}
}
@SmallTest
public void testDeleteAllCacheFiles() {
String testName="testDeleteAllCacheFiles";
cleanUpCacheDirectory();
}
void failStr(String errMsg) {
Log.w(TAG, "errMsg="+errMsg);
fail(errMsg);
}
void failStr(Exception e) {
Log.w(TAG, "e.getMessage="+e.getMessage());
Log.w(TAG, "e="+e);
}
long getFreeStorageBlks(StatFs st) {
st.restat("/data");
return st.getFreeBlocks();
}
long getFreeStorageSize(StatFs st) {
st.restat("/data");
return (st.getFreeBlocks()*st.getBlockSize());
}
@LargeTest
public void testFreeApplicationCacheAllFiles() throws Exception {
boolean TRACKING = true;
StatFs st = new StatFs("/data");
long blks1 = getFreeStorageBlks(st);
long availableMem = getFreeStorageSize(st);
File cacheDir = mContext.getCacheDir();
assertNotNull(cacheDir);
createTestFiles1(cacheDir, "testtmpdir", 5);
long blks2 = getFreeStorageBlks(st);
if(localLOGV || TRACKING) Log.i(TAG, "blk1="+blks1+", blks2="+blks2);
//this should free up the test files that were created earlier
invokePMFreeApplicationCache(availableMem);
long blks3 = getFreeStorageBlks(st);
if(localLOGV || TRACKING) Log.i(TAG, "blks3="+blks3);
verifyTestFiles1(cacheDir, "testtmpdir", 5);
}
@LargeTest
public void testFreeApplicationCacheSomeFiles() throws Exception {
StatFs st = new StatFs("/data");
long blks1 = getFreeStorageBlks(st);
File cacheDir = mContext.getCacheDir();
assertNotNull(cacheDir);
createTestFiles1(cacheDir, "testtmpdir", 5);
long blks2 = getFreeStorageBlks(st);
Log.i(TAG, "blk1="+blks1+", blks2="+blks2);
long diff = (blks1-blks2-2);
assertTrue(invokePMFreeApplicationCache(diff*st.getBlockSize()));
long blks3 = getFreeStorageBlks(st);
//blks3 should be greater than blks2 and less than blks1
if(!((blks3 <= blks1) && (blks3 >= blks2))) {
failStr("Expected "+(blks1-blks2)+" number of blocks to be freed but freed only "
+(blks1-blks3));
}
}
/**
* This method opens an output file writes to it, opens the same file as an input
* stream, reads the contents and verifies the data that was written earlier can be read
*/
public void openOutFileInAppFilesDir(File pFile, String pFileOut) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(pFile);
} catch (FileNotFoundException e1) {
failStr("Error when opening file "+e1);
return;
}
try {
fos.write(pFileOut.getBytes());
fos.close();
} catch (FileNotFoundException e) {
failStr(e.getMessage());
} catch (IOException e) {
failStr(e.getMessage());
}
int count = pFileOut.getBytes().length;
byte[] buffer = new byte[count];
try {
FileInputStream fis = new FileInputStream(pFile);
fis.read(buffer, 0, count);
fis.close();
} catch (FileNotFoundException e) {
failStr("Failed when verifing output opening file "+e.getMessage());
} catch (IOException e) {
failStr("Failed when verifying output, reading from written file "+e);
}
String str = new String(buffer);
assertEquals(str, pFileOut);
}
/*
* This test case verifies that output written to a file
* using Context.openFileOutput has executed successfully.
* The operation is verified by invoking Context.openFileInput
*/
@MediumTest
public void testAppFilesCreateFile() {
String fileName = "testFile1.txt";
String fileOut = "abcdefghijklmnopqrstuvwxyz";
Context con = super.getContext();
try {
FileOutputStream fos = con.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
failStr(e);
} catch (IOException e) {
failStr(e);
}
}
@SmallTest
public void testAppCacheCreateFile() {
String fileName = "testFile1.txt";
String fileOut = "abcdefghijklmnopqrstuvwxyz";
Context con = super.getContext();
File file = new File(con.getCacheDir(), fileName);
openOutFileInAppFilesDir(file, fileOut);
cleanUpCacheDirectory();
}
@MediumTest
public void testAppCreateCacheFiles() {
File cacheDir = mContext.getCacheDir();
String testDirName = "testtmp";
File testTmpDir = new File(cacheDir, testDirName);
testTmpDir.mkdir();
int numDirs = 3;
File fileArr[] = new File[numDirs];
for(int i = 0; i < numDirs; i++) {
fileArr[i] = new File(testTmpDir, "dir"+(i+1));
fileArr[i].mkdir();
}
byte buffer[] = getBuffer();
Log.i(TAG, "Size of bufer="+buffer.length);
for(int i = 0; i < numDirs; i++) {
for(int j = 1; j <= (i); j++) {
File file1 = new File(fileArr[i], "testFile"+j+".txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file1);
for(int k = 1; k < 10; k++) {
fos.write(buffer);
}
Log.i(TAG, "wrote 10K bytes to "+file1);
fos.close();
} catch (FileNotFoundException e) {
Log.i(TAG, "Excetion ="+e);
fail("Error when creating outputstream "+e);
} catch(IOException e) {
Log.i(TAG, "Excetion ="+e);
fail("Error when writing output "+e);
}
}
}
}
byte[] getBuffer() {
String sbuffer = "a";
for(int i = 0; i < 10; i++) {
sbuffer += sbuffer;
}
return sbuffer.getBytes();
}
long getFileNumBlocks(long fileSize, int blkSize) {
long ret = fileSize/blkSize;
if(ret*blkSize < fileSize) {
ret++;
}
return ret;
}
//@LargeTest
public void testAppCacheClear() {
String dataDir="/data/data";
StatFs st = new StatFs(dataDir);
int blkSize = st.getBlockSize();
int totBlks = st.getBlockCount();
long availableBlks = st.getFreeBlocks();
long thresholdBlks = (totBlks*THRESHOLD)/100;
String testDirName = "testdir";
//create directory in cache
File testDir = new File(mContext.getCacheDir(), testDirName);
testDir.mkdirs();
byte[] buffer = getBuffer();
int i = 1;
if(localLOGV) Log.i(TAG, "availableBlks="+availableBlks+", thresholdBlks="+thresholdBlks);
long createdFileBlks = 0;
int imax = 300;
while((availableBlks > thresholdBlks) &&(i < imax)) {
File testFile = new File(testDir, "testFile"+i+".txt");
if(localLOGV) Log.i(TAG, "Creating "+i+"th test file "+testFile);
int jmax = i;
i++;
FileOutputStream fos;
try {
fos = new FileOutputStream(testFile);
} catch (FileNotFoundException e) {
Log.i(TAG, "Failed creating test file:"+testFile);
continue;
}
boolean err = false;
for(int j = 1; j <= jmax;j++) {
try {
fos.write(buffer);
} catch (IOException e) {
Log.i(TAG, "Failed to write to file:"+testFile);
err = true;
}
}
try {
fos.close();
} catch (IOException e) {
Log.i(TAG, "Failed closing file:"+testFile);
}
if(err) {
continue;
}
createdFileBlks += getFileNumBlocks(testFile.length(), blkSize);
st.restat(dataDir);
availableBlks = st.getFreeBlocks();
}
st.restat(dataDir);
long availableBytes = st.getFreeBlocks()*blkSize;
long shouldFree = (ACTUAL_THRESHOLD-THRESHOLD)*totBlks;
//would have run out of memory
//wait for some time and confirm cache is deleted
try {
Log.i(TAG, "Sleeping for 2 minutes...");
Thread.sleep(2*60*1000);
} catch (InterruptedException e) {
fail("Exception when sleeping "+e);
}
boolean removedFlag = false;
long existingFileBlks = 0;
for(int k = 1; k <i; k++) {
File testFile = new File(testDir, "testFile"+k+".txt");
if(!testFile.exists()) {
removedFlag = true;
if(localLOGV) Log.i(TAG, testFile+" removed");
} else {
existingFileBlks += getFileNumBlocks(testFile.length(), blkSize);
}
}
if(localLOGV) Log.i(TAG, "createdFileBlks="+createdFileBlks+
", existingFileBlks="+existingFileBlks);
long fileSize = createdFileBlks-existingFileBlks;
//verify fileSize number of bytes have been cleared from cache
if(localLOGV) Log.i(TAG, "deletedFileBlks="+fileSize+" shouldFreeBlks="+shouldFree);
if((fileSize > (shouldFree-blkSize) && (fileSize < (shouldFree+blkSize)))) {
Log.i(TAG, "passed");
}
assertTrue(removedFlag);
}
//createTestFiles(new File(super.getContext().getCacheDir(), "testtmp", "dir", 3)
void createTestFiles1(File cacheDir, String testFilePrefix, int numTestFiles) {
byte buffer[] = getBuffer();
for(int i = 0; i < numTestFiles; i++) {
File file1 = new File(cacheDir, testFilePrefix+i+".txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file1);
for(int k = 1; k < 10; k++) {
fos.write(buffer);
}
fos.close();
} catch (FileNotFoundException e) {
Log.i(TAG, "Exception ="+e);
fail("Error when creating outputstream "+e);
} catch(IOException e) {
Log.i(TAG, "Exception ="+e);
fail("Error when writing output "+e);
}
try {
//introduce sleep for 1 s to avoid common time stamps for files being created
Thread.sleep(1000);
} catch (InterruptedException e) {
fail("Exception when sleeping "+e);
}
}
}
void verifyTestFiles1(File cacheDir, String testFilePrefix, int numTestFiles) {
for(int i = 0; i < numTestFiles; i++) {
File file1 = new File(cacheDir, testFilePrefix+i+".txt");
if(file1.exists()) {
fail("file:"+file1+" should not exist");
}
}
}
void createTestFiles2(File cacheDir, String rootTestDirName, String subDirPrefix, int numDirs, String testFilePrefix) {
Context con = super.getContext();
File testTmpDir = new File(cacheDir, rootTestDirName);
testTmpDir.mkdir();
File fileArr[] = new File[numDirs];
for(int i = 0; i < numDirs; i++) {
fileArr[i] = new File(testTmpDir, subDirPrefix+(i+1));
fileArr[i].mkdir();
}
byte buffer[] = getBuffer();
for(int i = 0; i < numDirs; i++) {
for(int j = 1; j <= (i); j++) {
File file1 = new File(fileArr[i], testFilePrefix+j+".txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file1);
for(int k = 1; k < 10; k++) {
fos.write(buffer);
}
fos.close();
} catch (FileNotFoundException e) {
Log.i(TAG, "Exception ="+e);
fail("Error when creating outputstream "+e);
} catch(IOException e) {
Log.i(TAG, "Exception ="+e);
fail("Error when writing output "+e);
}
try {
//introduce sleep for 10 ms to avoid common time stamps for files being created
Thread.sleep(10);
} catch (InterruptedException e) {
fail("Exception when sleeping "+e);
}
}
}
}
class PackageDataObserver extends IPackageDataObserver.Stub {
public boolean retValue = false;
private boolean doneFlag = false;
public void onRemoveCompleted(String packageName, boolean succeeded)
throws RemoteException {
synchronized(this) {
retValue = succeeded;
doneFlag = true;
notifyAll();
}
}
public boolean isDone() {
return doneFlag;
}
}
IPackageManager getPm() {
return IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
}
boolean invokePMDeleteAppCacheFiles() throws Exception {
try {
String packageName = mContext.getPackageName();
PackageDataObserver observer = new PackageDataObserver();
//wait on observer
synchronized(observer) {
getPm().deleteApplicationCacheFiles(packageName, observer);
long waitTime = 0;
while(!observer.isDone() || (waitTime > MAX_WAIT_TIME)) {
observer.wait(WAIT_TIME_INCR);
waitTime += WAIT_TIME_INCR;
}
if(!observer.isDone()) {
throw new Exception("timed out waiting for PackageDataObserver.onRemoveCompleted");
}
}
return observer.retValue;
} catch (RemoteException e) {
Log.w(TAG, "Failed to get handle for PackageManger Exception: "+e);
return false;
} catch (InterruptedException e) {
Log.w(TAG, "InterruptedException :"+e);
return false;
}
}
boolean invokePMFreeApplicationCache(long idealStorageSize) throws Exception {
try {
String packageName = mContext.getPackageName();
PackageDataObserver observer = new PackageDataObserver();
//wait on observer
synchronized(observer) {
getPm().freeStorageAndNotify(idealStorageSize, observer);
long waitTime = 0;
while(!observer.isDone() || (waitTime > MAX_WAIT_TIME)) {
observer.wait(WAIT_TIME_INCR);
waitTime += WAIT_TIME_INCR;
}
if(!observer.isDone()) {
throw new Exception("timed out waiting for PackageDataObserver.onRemoveCompleted");
}
}
return observer.retValue;
} catch (RemoteException e) {
Log.w(TAG, "Failed to get handle for PackageManger Exception: "+e);
return false;
} catch (InterruptedException e) {
Log.w(TAG, "InterruptedException :"+e);
return false;
}
}
boolean invokePMFreeStorage(long idealStorageSize, FreeStorageReceiver r,
PendingIntent pi) throws Exception {
try {
// Spin lock waiting for call back
synchronized(r) {
getPm().freeStorage(idealStorageSize, pi);
long waitTime = 0;
while(!r.isDone() && (waitTime < MAX_WAIT_TIME)) {
r.wait(WAIT_TIME_INCR);
waitTime += WAIT_TIME_INCR;
}
if(!r.isDone()) {
throw new Exception("timed out waiting for call back from PendingIntent");
}
}
return r.getResultCode() == 1;
} catch (RemoteException e) {
Log.w(TAG, "Failed to get handle for PackageManger Exception: "+e);
return false;
} catch (InterruptedException e) {
Log.w(TAG, "InterruptedException :"+e);
return false;
}
}
@LargeTest
public void testDeleteAppCacheFiles() throws Exception {
String testName="testDeleteAppCacheFiles";
File cacheDir = mContext.getCacheDir();
createTestFiles1(cacheDir, "testtmpdir", 5);
assertTrue(invokePMDeleteAppCacheFiles());
//confirm files dont exist
verifyTestFiles1(cacheDir, "testtmpdir", 5);
}
class PackageStatsObserver extends IPackageStatsObserver.Stub {
public boolean retValue = false;
public PackageStats stats;
private boolean doneFlag = false;
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
throws RemoteException {
synchronized(this) {
retValue = succeeded;
stats = pStats;
doneFlag = true;
notifyAll();
}
}
public boolean isDone() {
return doneFlag;
}
}
public PackageStats invokePMGetPackageSizeInfo() throws Exception {
try {
String packageName = mContext.getPackageName();
PackageStatsObserver observer = new PackageStatsObserver();
//wait on observer
synchronized(observer) {
getPm().getPackageSizeInfo(packageName, observer);
long waitTime = 0;
while((!observer.isDone()) || (waitTime > MAX_WAIT_TIME) ) {
observer.wait(WAIT_TIME_INCR);
waitTime += WAIT_TIME_INCR;
}
if(!observer.isDone()) {
throw new Exception("Timed out waiting for PackageStatsObserver.onGetStatsCompleted");
}
}
if(localLOGV) Log.i(TAG, "OBSERVER RET VALUES code="+observer.stats.codeSize+
", data="+observer.stats.dataSize+", cache="+observer.stats.cacheSize);
return observer.stats;
} catch (RemoteException e) {
Log.w(TAG, "Failed to get handle for PackageManger Exception: "+e);
return null;
} catch (InterruptedException e) {
Log.w(TAG, "InterruptedException :"+e);
return null;
}
}
@SmallTest
public void testGetPackageSizeInfo() throws Exception {
String testName="testGetPackageSizeInfo";
PackageStats stats = invokePMGetPackageSizeInfo();
assertTrue(stats!=null);
//confirm result
if(localLOGV) Log.i(TAG, "code="+stats.codeSize+", data="+stats.dataSize+
", cache="+stats.cacheSize);
}
@SmallTest
public void testGetSystemSharedLibraryNames() throws Exception {
try {
String[] sharedLibs = getPm().getSystemSharedLibraryNames();
if (localLOGV) {
for (String str : sharedLibs) {
Log.i(TAG, str);
}
}
} catch (RemoteException e) {
fail("Failed invoking getSystemSharedLibraryNames with exception:" + e);
}
}
class FreeStorageReceiver extends BroadcastReceiver {
public static final String ACTION_FREE = "com.android.unit_tests.testcallback";
private boolean doneFlag = false;
public boolean isDone() {
return doneFlag;
}
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase(ACTION_FREE)) {
if (localLOGV) Log.i(TAG, "Got notification: clear cache succeeded "+getResultCode());
synchronized (this) {
doneFlag = true;
notifyAll();
}
}
}
}
@SmallTest
public void testFreeStorage() throws Exception {
boolean TRACKING = true;
StatFs st = new StatFs("/data");
long blks1 = getFreeStorageBlks(st);
if(localLOGV || TRACKING) Log.i(TAG, "Available free blocks="+blks1);
long availableMem = getFreeStorageSize(st);
File cacheDir = mContext.getCacheDir();
assertNotNull(cacheDir);
createTestFiles1(cacheDir, "testtmpdir", 5);
long blks2 = getFreeStorageBlks(st);
if(localLOGV || TRACKING) Log.i(TAG, "Available blocks after writing test files in application cache="+blks2);
// Create receiver and register it
FreeStorageReceiver receiver = new FreeStorageReceiver();
mContext.registerReceiver(receiver, new IntentFilter(FreeStorageReceiver.ACTION_FREE));
PendingIntent pi = PendingIntent.getBroadcast(mContext,
0, new Intent(FreeStorageReceiver.ACTION_FREE), 0);
// Invoke PackageManager api
invokePMFreeStorage(availableMem, receiver, pi);
long blks3 = getFreeStorageBlks(st);
if(localLOGV || TRACKING) Log.i(TAG, "Available blocks after freeing cache"+blks3);
assertEquals(receiver.getResultCode(), 1);
mContext.unregisterReceiver(receiver);
// Verify result
verifyTestFiles1(cacheDir, "testtmpdir", 5);
}
/* utility method used to create observer and check async call back from PackageManager.
* ClearApplicationUserData
*/
boolean invokePMClearApplicationUserData() throws Exception {
try {
String packageName = mContext.getPackageName();
PackageDataObserver observer = new PackageDataObserver();
//wait on observer
synchronized(observer) {
getPm().clearApplicationUserData(packageName, observer);
long waitTime = 0;
while(!observer.isDone() || (waitTime > MAX_WAIT_TIME)) {
observer.wait(WAIT_TIME_INCR);
waitTime += WAIT_TIME_INCR;
}
if(!observer.isDone()) {
throw new Exception("timed out waiting for PackageDataObserver.onRemoveCompleted");
}
}
return observer.retValue;
} catch (RemoteException e) {
Log.w(TAG, "Failed to get handle for PackageManger Exception: "+e);
return false;
} catch (InterruptedException e) {
Log.w(TAG, "InterruptedException :"+e);
return false;
}
}
void verifyUserDataCleared(File pDir) {
if(localLOGV) Log.i(TAG, "Verifying "+pDir);
if(pDir == null) {
return;
}
String fileList[] = pDir.list();
if(fileList == null) {
return;
}
int imax = fileList.length;
//look recursively in user data dir
for(int i = 0; i < imax; i++) {
if(localLOGV) Log.i(TAG, "Found entry "+fileList[i]+ "in "+pDir);
if("lib".equalsIgnoreCase(fileList[i])) {
if(localLOGV) Log.i(TAG, "Ignoring lib directory");
continue;
}
fail(pDir+" should be empty or contain only lib subdirectory. Found "+fileList[i]);
}
}
File getDataDir() {
try {
ApplicationInfo appInfo = getPm().getApplicationInfo(mContext.getPackageName(), 0);
return new File(appInfo.dataDir);
} catch (RemoteException e) {
throw new RuntimeException("Pacakge manager dead", e);
}
}
@LargeTest
public void testClearApplicationUserDataWithTestData() throws Exception {
File cacheDir = mContext.getCacheDir();
createTestFiles1(cacheDir, "testtmpdir", 5);
if(localLOGV) {
Log.i(TAG, "Created test data Waiting for 60seconds before continuing");
Thread.sleep(60*1000);
}
assertTrue(invokePMClearApplicationUserData());
//confirm files dont exist
verifyUserDataCleared(getDataDir());
}
@SmallTest
public void testClearApplicationUserDataWithNoTestData() throws Exception {
assertTrue(invokePMClearApplicationUserData());
//confirm files dont exist
verifyUserDataCleared(getDataDir());
}
@LargeTest
public void testClearApplicationUserDataNoObserver() throws Exception {
getPm().clearApplicationUserData(mContext.getPackageName(), null);
//sleep for 1 minute
Thread.sleep(60*1000);
//confirm files dont exist
verifyUserDataCleared(getDataDir());
}
}
|